c# xml 转 json
在C#中,可以使用下面几种方法将XML转换为JSON:
-
使用Newtonsoft.Json库:
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.Xml; // 从XML字符串转换为JSON字符串 string xmlString = "<root><name>John</name><age>30</age></root>"; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlString); string jsonString = JsonConvert.SerializeXmlNode(xml); // 从XML文件转换为JSON字符串 string xmlFilePath = "path/to/xml/file.xml"; XmlDocument xml = new XmlDocument(); xml.Load(xmlFilePath); string jsonString = JsonConvert.SerializeXmlNode(xml); // 从XML字符串转换为JObject string xmlString = "<root><name>John</name><age>30</age></root>"; XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlString); JObject jsonObject = JObject.Parse(JsonConvert.SerializeXmlNode(xml)); // 从XML文件转换为JObject string xm