XML与JSON的转换
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(); } }
XML与JSON的转换
本文2024-09-16 17:42:56发表“云星空知识”栏目。
本文链接:https://wenku.my7c.com/article/kingdee-k3cloud-17487.html