Home > Backend Development > C++ > body text

How to convert XML to Json and Json back to XML using Newtonsoft.json?

WBOY
Release: 2023-09-12 19:01:06
forward
1016 people have browsed it

如何使用 Newtonsoft.json 将 XML 转换为 Json 以及将 Json 转换回 XML?

Json.NET supports using XmlNodeConverter to convert JSON to XML and vice versa.

Elements, attributes, text, comments, character data, processing instructions, namespaces and XML declarations are preserved between the two during conversion

SerializeXmlNode

JsonConvert has two A helper method for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it into JSON text.

DeserializeXmlNode

The second helper method on JsonConvert is DeserializeXmlNode(). This method takes the JSON text and deserializes it into an XmlNode.

Example 1

static void Main(string[] args) {
   string xml = @"Alanhttp://www.google1.com Admin1";
   XmlDocument doc = new XmlDocument();
   doc.LoadXml(xml);
   string json = JsonConvert.SerializeXmlNode(doc);
   Console.WriteLine(json);
   Console.ReadLine();
}
Copy after login

Output

{"person":{"@id":"1","name":"Alan","url":"http://www.google1.com","role":"Admin1"}}
Copy after login

Example 2

static void Main(string[] args) {
   string json = @"{
      '?xml': {
         '@version': '1.0',
         '@standalone': 'no'
      },
      'root': {
         'person': [
            {
            '@id': '1',
            'name': 'Alan',
            'url': 'http://www.google1.com'
            },
            {
            '@id': '2',
            'name': 'Louis',
            'url': 'http://www.yahoo1.com'
            }
         ]
      }
   }";
   XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
   Console.WriteLine(json);
   Console.ReadLine();
}
Copy after login

Output

'?xml': {
   '@version': '1.0',
   '@standalone': 'no'
},
'root': {
   'person': [
      {
      '@id': '1',
      'name': 'Alan',
      'url': 'http://www.google1.com'
      },
      {
      '@id': '2',
      'name': 'Louis',
      'url': 'http://www.yahoo1.com'
      }
   ]
}
Copy after login

The above is the detailed content of How to convert XML to Json and Json back to XML using Newtonsoft.json?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template