using PTMedicalInsurance.Variables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace PTMedicalInsurance.Helper
{
class XmlHelper
{
/// <summary>
/// 组织中心入参
/// </summary>
/// <param name="infno"></param>
/// <param name="input"></param>
/// <returns></returns>
public string setInput(XElement xInput)
{
XDocument XDoc = new XDocument();
XDoc.Add(xInput);
XDoc.Declaration = new XDeclaration("1.0", "GBK", "yes");
return XDoc.ToStringWithDeclaration(); //扩展方法 https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
}
/// <summary>
/// 根据JSonPath查找节点值,如果节点不存在则返回空值
/// </summary>
/// <param name="jo"></param>
/// <param name="jsonPath"></param>
/// <returns></returns>
public string getDestValue(string source, string destPath)
{
try
{
XDocument XDoc = XDocument.Parse(source);
XElement XDest = XDoc.XPathSelectElement(destPath);
if (XDest != null)
return XDest.Value;
else
return "节点为空!";
}
catch (Exception ex)
{
return "查找XML节点异常:" + ex.Message;
}
}
public string ToJSON(string source)
{
string json = "";
try
{
source = Regex.Replace(source, "<row",
"<row xmlns:json=\"http://james.newtonking.com/projects/json\" json:Array=\"true\" ", RegexOptions.IgnoreCase);
XDocument xDoc = XDocument.Parse(source);
json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xDoc.ToXmlDocument());
return json;
}
catch (Exception ex)
{
return "转换异常:" + ex.Message;
}
finally
{
Global.writeLog("XMLToJSON", source,json);
}
}
public string ToXML(string jsonSource)
{
try
{
XmlDocument xe = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonSource);
return xe.OuterXml;
}
catch (Exception ex)
{
return "转换异常:" + ex.Message;
}
}
}
public static class MyExtensions
{
/// <summary>
/// Doc输出无声明,强行补上
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
public static string ToStringWithDeclaration(this XDocument doc)
{
return doc.Declaration.ToString() + Environment.NewLine + doc.ToString();
}
/// <summary>
/// 无缩进格式(压缩格式)
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
public static string ToCompressString(this XDocument doc)
{
return doc.Declaration.ToString() + doc.ToString(SaveOptions.DisableFormatting);
}
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
}