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 { /// /// 组织中心入参 /// /// /// /// 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 } /// /// 根据JSonPath查找节点值,如果节点不存在则返回空值 /// /// /// /// 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, " /// Doc输出无声明,强行补上 /// /// /// public static string ToStringWithDeclaration(this XDocument doc) { return doc.Declaration.ToString() + Environment.NewLine + doc.ToString(); } /// /// 无缩进格式(压缩格式) /// /// /// 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); } } } }