How to convert JSON to XML or XML to JSON?

后端 未结 13 1295
借酒劲吻你
借酒劲吻你 2020-11-22 05:43

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to X

13条回答
  •  不要未来只要你来
    2020-11-22 06:25

    For convert JSON string to XML try this:

        public string JsonToXML(string json)
        {
            XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
            XElement root = new XElement("Root");
            root.Name = "Result";
    
            var dataTable = JsonConvert.DeserializeObject(json);
            root.Add(
                     from row in dataTable.AsEnumerable()
                     select new XElement("Record",
                                         from column in dataTable.Columns.Cast()
                                         select new XElement(column.ColumnName, row[column])
                                        )
                   );
    
    
            xmlDoc.Add(root);
            return xmlDoc.ToString();
        }
    

    For convert XML to JSON try this:

        public string XmlToJson(string xml)
        {
           XmlDocument doc = new XmlDocument();
           doc.LoadXml(xml);
    
           string jsonText = JsonConvert.SerializeXmlNode(doc);
           return jsonText;
         }
    

提交回复
热议问题