From Json.NET documentation: http://james.newtonking.com/projects/json/help/?topic=html/ConvertingJSONandXML.htm

You can force a node to be rendered as an Array by adding the attribute json:Array='true' to the XML node you are converting to JSON. Also, you need to declare the json prefix namespace at the XML header xmlns:json='http://james.newtonking.com/projects/json' or else you will get an XML error stating that the json prefix is not declared.

The next example is provided by the documentation:

xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
        <name>Alan</name>
        <url>http://www.google.com</url>
        <role json:Array='true'>Admin</role>
      </person>";

Generated output:

{
  "person": {
    "@id": "1",
    "name": "Alan",
    "url": "http://www.google.com",
    "role": [
      "Admin"
    ]
  }
}
Answer from Iván Pérez Gómez on Stack Overflow
🌐
GitHub
github.com › JamesNK › Newtonsoft.Json › issues › 1734
JSON to XML converting with custom tag, JSON:array attribute is not added · Issue #1734 · JamesNK/Newtonsoft.Json
April 25, 2018 - Resulting XML is added below · <?xml version="1.0"?> <Test_Service> <fname>mark</fname> <lname>joye</lname> <CarCompany>saab</CarCompany> <CarNumber>9741</CarNumber> <IsInsured>true</IsInsured> <safty>ABS</safty> <safty>AirBags</safty> <safty>childdoorlock</safty> <CarDescription>test Car</CarDescription> <collections xmlns:json="http://james.newtonking.com/projects/json" json:Array="true"> <XYZ>1</XYZ> <PQR>11</PQR> <contactdetails> <contname>DOM</contname> <contnumber>8787</contnumber> </contactdetails> <contactdetails> <contname>COM</contname> <contnumber>4564</contnumber> <addtionaldetail
Author   vatsaldesai
Top answer
1 of 6
27

From Json.NET documentation: http://james.newtonking.com/projects/json/help/?topic=html/ConvertingJSONandXML.htm

You can force a node to be rendered as an Array by adding the attribute json:Array='true' to the XML node you are converting to JSON. Also, you need to declare the json prefix namespace at the XML header xmlns:json='http://james.newtonking.com/projects/json' or else you will get an XML error stating that the json prefix is not declared.

The next example is provided by the documentation:

xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
        <name>Alan</name>
        <url>http://www.google.com</url>
        <role json:Array='true'>Admin</role>
      </person>";

Generated output:

{
  "person": {
    "@id": "1",
    "name": "Alan",
    "url": "http://www.google.com",
    "role": [
      "Admin"
    ]
  }
}
2 of 6
16

Giving my +1 to Iván Pérez Gómez and providing some code here to support his answer:

Add the required json.net namespace to the root node:

private static void AddJsonNetRootAttribute(XmlDocument xmlD)
    {
        XmlAttribute jsonNS = xmlD.CreateAttribute("xmlns", "json", "http://www.w3.org/2000/xmlns/");
        jsonNS.Value = "http://james.newtonking.com/projects/json";

        xmlD.DocumentElement.SetAttributeNode(jsonNS);
    }

And to add json:Array attribute to elements found by xpath:

private static void AddJsonArrayAttributesForXPath(string xpath, XmlDocument doc)
    {
        var elements = doc.SelectNodes(xpath);



        foreach (var element in elements)
        {
            var el = element as XmlElement;

            if (el != null)
            {

                var jsonArray = doc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json");
                jsonArray.Value = "true";
                el.SetAttributeNode(jsonArray);
            }
        }
    }

Here is a sample of a single child node as a json array:

🌐
Newtonsoft
newtonsoft.com › json › help › html › ConvertXmlToJsonForceArray.htm
Convert XML to JSON and force array
string xml = @"<person id='1'> <name>Alan</name> <url>http://www.google.com</url> <role>Admin1</role> </person>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": "Admin1" // } // } xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1'> <name>Alan</name> <url>http://www.google.com</url> <role json:Array='true'>Admin</role> </person>"; doc = new XmlDocument(); doc.LoadXml(xml); json = JsonConvert.SerializeXmlNode(doc); Console.WriteLine(json); // { // "person": { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com", // "role": [ // "Admin" // ] // } // }
🌐
Stack Overflow
stackoverflow.com › questions › 53783053 › force-root-xml-element-to-be-array-on-json-conversion
Force root xml element to be array on json conversion - Stack Overflow
Since you are already adding this attribute to <role> adding it to the root element as well should not be a burden. Loading the XML into an XDocument (or XmlDocument) and converting the document itself rather than just the root element XDocument.Root. ... var xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1' json:Array='true'> <name>Alan</name> <url>http://www.google.com</url> <role json:Array='true'>Admin</role> </person>"; var xDocument = XDocument.Parse(xml); var json1 = JsonConvert.SerializeXNode(xDocument, Newtonsoft.Json.Formatting.Indented);
Find elsewhere
🌐
GitHub
github.com › stleary › JSON-java › issues › 235
XML to json Array Issue · Issue #235 · stleary/JSON-java
June 2, 2016 - I need to parse a specific XML element of xml content, that has only one occurency, to a JSON Array object, using XML.toJSONObject(xml). How do this? When the XML element appears more than one occurence, it's work fine!
Author   smtrad
Top answer
1 of 12
499

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

2 of 12
60

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

Top answer
1 of 2
2

DeserializeXmlNode() doesn't really have a way to customize the way it does its JSON to XML conversion. To get the result you want using that method, you will either have to manipulate the JSON before converting it to XML, or manipulate the XML afterwards.

In this case, I think it might be easier to use Json.Net's LINQ-to-JSON API to build the XML directly from the JSON in the shape you want. You can do it like this:

var ja = JArray.Parse(jsonResult);
var xml = new XDocument(
    new XElement("cars", 
        ja.Select(c => 
            new XElement("car",
                new XElement("features", 
                    c["car"]["features"].Select(f => 
                        new XElement("feature", 
                            new XElement("code", (string)f["code"])
                        )
                    )
                )
            )
        )
    )
);

Console.WriteLine(xml.ToString());

Fiddle: https://dotnetfiddle.net/fxxQnL

2 of 2
0

With Cinchoo ETL - an open source library, you can do the Xml to Json easily with few lines of code

string json = @"
[
    {
        ""car"": {
            ""features"": [{
                ""code"": ""1""
            }, {
                ""code"": ""2""
            }]
        }
    },
    {
        ""car"": {
            ""features"": [{
                ""code"": ""3""
            }, {
                ""code"": ""2""
            }]
        }
    }
]";
StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json))
{
    using (var w = new ChoXmlWriter(sb)
        .Configure(c => c.RootName = "cars")
        //.Configure(c => c.IgnoreRootName = true)
        .Configure(c => c.IgnoreNodeName = true)
        )
    {
        w.Write(p);
    }
}
Console.WriteLine(sb.ToString());

Output:

<cars>
  <car>
    <features>
      <feature>
        <code>1</code>
      </feature>
      <feature>
        <code>2</code>
      </feature>
    </features>
  </car>
  <car>
    <features>
      <feature>
        <code>3</code>
      </feature>
      <feature>
        <code>2</code>
      </feature>
    </features>
  </car>
</cars>

Checkout CodeProject article for some additional help.

Disclaimer: I'm the author of this library.

🌐
OutSystems
outsystems.com › forums › discussion › 82490 › xmltojson-single-element-to-json-array-error
[XmlToJson] Single Element to JSON array Error | OutSystems
I've been encountering this problem where an element from the Xml can either have one or more items inside it, so when I convert it into Json: · One item translates to { "name" : "value" } while multiple items translate to [ { "name" : "value" } ]
🌐
GitHub
github.com › stleary › JSON-java › issues › 330
Having issue while convertnig xml with single element to json array or vice versa · Issue #330 · stleary/JSON-java
March 20, 2017 - but, we need similar behavior while converting json to xml and back again where json array is having single element i.e.
Author   rvashishth
🌐
Newtonsoft
newtonsoft.com › json › help › html › ConvertingJSONandXML.htm
Converting between JSON and XML
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. ... The JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode.
🌐
Code Maze
code-maze.com › home › how to convert json to xml or xml to json in c#
How to Convert JSON to XML or XML to JSON in C# - Code Maze
June 9, 2022 - This allows us to set a flag attribute json:Array to true on the target element (Stars tag in our case). During serialization this attribute instructs the converter to forcefully interpret it as a JSON array: { "?xml": { "@version": "1.0" }, "SquidGame": { "Genre": "Thriller", "Rating": { "@Type": "Imdb", "#text": "8.1" }, "Stars": ["Lee Jung-jae"], "Budget": null } } As we expect, the JSON result now holds Stars in an array.