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(); } }
推荐阅读