XML与JSON的转换原创
金蝶云社区-碎银几两
碎银几两
0人赞赏了该文章 5次浏览 未经作者许可,禁止转载编辑于2024年08月22日 08:14:13

using System; using System.Xml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class Program {     static void Main()     {         // JSON 转 XML         string json = "{\"name\":\"Alice\",\"age\":25}";         XmlDocument xmlDoc = JsonToXml(json);         Console.WriteLine(xmlDoc.OuterXml);         // XML 转 JSON         string xml = "<person><name>Bob</name><age>30</age></person>";         string jsonResult = XmlToJson(xml);         Console.WriteLine(jsonResult);     }     static XmlDocument JsonToXml(string json)     {         JObject jsonObject = JObject.Parse(json);         XmlDocument xmlDoc = new XmlDocument();         XmlElement root = xmlDoc.CreateElement("root");         xmlDoc.AppendChild(root);         foreach (var property in jsonObject.Properties())         {             XmlElement element = xmlDoc.CreateElement(property.Name);             element.InnerText = property.Value.ToString();             root.AppendChild(element);         }         return xmlDoc;     }     static string XmlToJson(string xml)     {         XmlDocument xmlDoc = new XmlDocument();         xmlDoc.LoadXml(xml);         JObject jsonObject = new JObject();         foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)         {             jsonObject.Add(node.Name, node.InnerText);         }         return jsonObject.ToString();     } }


赞 0