Click or drag to resize
Json.NETConverting between JSON and XML
 

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

Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the two. The only caveat is that it is possible to lose the order of differently named nodes at the same level when they are grouped together into an array.

Conversion Rules
  • Elements remain unchanged.

  • Attributes are prefixed with an @ and should be at the start of the object.

  • Single child text nodes are a value directly against an element, otherwise they are accessed via #text.

  • The XML declaration and processing instructions are prefixed with ?.

  • Character data, comments, whitespace and significant whitespace nodes are accessed via #cdata-section, #comment, #whitespace and #significant-whitespace respectively.

  • Multiple nodes with the same name at the same level are grouped together into an array.

  • Empty elements are null.

If the XML created from JSON doesn't match what you want, then you will need to convert it manually. The best approach to do this is to load your JSON into a LINQ to JSON object like JObject or JArray and then use LINQ to create an XDocument. The opposite process, using LINQ with an XDocument to create a JObject or JArray, also works. You can find out more about using LINQ to JSON with LINQ here.

Note Note

The version of Json.NET being used in your application will change what XML conversion methods are available. SerializeXmlNode/DeserializeXmlNode are available when the framework supports XmlDocument; SerializeXNode/DeserializeXNode are available when the framework supports XDocument.

SerializeXmlNode

The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode. This method takes an XmlNode and serializes it to JSON text.

Converting XML to JSON with SerializeXmlNode
 1string xml = @"<?xml version='1.0' standalone='no'?>
 2<root>
 3  <person id='1'>
 4    <name>Alan</name>
 5    <url>http://www.google.com</url>
 6  </person>
 7  <person id='2'>
 8    <name>Louis</name>
 9    <url>http://www.yahoo.com</url>
10  </person>
11</root>";
12
13XmlDocument doc = new XmlDocument();
14doc.LoadXml(xml);
15
16string jsonText = JsonConvert.SerializeXmlNode(doc);
17//{
18//  "?xml": {
19//    "@version": "1.0",
20//    "@standalone": "no"
21//  },
22//  "root": {
23//    "person": [
24//      {
25//        "@id": "1",
26//        "name": "Alan",
27//        "url": "http://www.google.com"
28//      },
29//      {
30//        "@id": "2",
31//        "name": "Louis",
32//        "url": "http://www.yahoo.com"
33//      }
34//    ]
35//  }
36//}

Because multiple nodes with the same name at the same level are grouped together into an array, the conversion process can produce different JSON depending on the number of nodes. For example, if some XML for a user has a single <Role> node, then that role will be text against a JSON "Role" property, but if the user has multiple <Role> nodes, then the role values will be placed in a JSON array.

To fix this situation a custom XML attribute can be added to force a JSON array to be created.

Attribute to Force a JSON Array
 1string xml = @"<person id='1'>
 2  <name>Alan</name>
 3  <url>http://www.google.com</url>
 4  <role>Admin1</role>
 5</person>";
 6
 7XmlDocument doc = new XmlDocument();
 8doc.LoadXml(xml);
 9
10string json = JsonConvert.SerializeXmlNode(doc);
11//{
12//  "person": {
13//    "@id": "1",
14//    "name": "Alan",
15//    "url": "http://www.google.com",
16//    "role": "Admin1"
17//  }
18//}
19
20xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
21  <name>Alan</name>
22  <url>http://www.google.com</url>
23  <role json:Array='true'>Admin</role>
24</person>";
25
26doc = new XmlDocument();
27doc.LoadXml(xml);
28
29json = JsonConvert.SerializeXmlNode(doc);
30//{
31//  "person": {
32//    "@id": "1",
33//    "name": "Alan",
34//    "url": "http://www.google.com",
35//    "role": [
36//      "Admin"
37//    ]
38//  }
39//}
DeserializeXmlNode

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

Because valid XML must have one root element, the JSON passed to DeserializeXmlNode should have one property in the root JSON object. If the root JSON object has multiple properties, then the overload that also takes an element name should be used. A root element with that name will be inserted into the deserialized XmlNode.

Converting JSON to XML with DeserializeXmlNode
 1string json = @"{
 2  '?xml': {
 3    '@version': '1.0',
 4    '@standalone': 'no'
 5  },
 6  'root': {
 7    'person': [
 8      {
 9        '@id': '1',
10        'name': 'Alan',
11        'url': 'http://www.google.com'
12      },
13      {
14        '@id': '2',
15        'name': 'Louis',
16        'url': 'http://www.yahoo.com'
17      }
18    ]
19  }
20}";
21
22XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
23// <?xml version="1.0" standalone="no"?>
24// <root>
25//   <person id="1">
26//     <name>Alan</name>
27//     <url>http://www.google.com</url>
28//   </person>
29//   <person id="2">
30//     <name>Louis</name>
31//     <url>http://www.yahoo.com</url>
32//   </person>
33// </root>
See Also