Convert JSON array to XML

I am trying to convert JSON to XML. My JSON contains an array of cars, and each car has many features:

[
    {
        "car": {
            "features": [{
                "code": "1"
            }, {
                "code": "2"
            }]
        }
    },
    {
        "car": {
            "features": [{
                "code": "3"
            }, {
                "code": "2"
            }]
        }
    }
]

I convert this to XML:

// the tag name for each top level element in the json array
var wrappedDocument = string.Format("{{ car: {0} }}", jsonResult);
// set the root tag name
return JsonConvert.DeserializeXmlNode(wrappedDocument, "cars");

This is the result of XML:

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

My problem is that I would like all the "functions" to be listed under the common element, just as the "car" is indicated under the "cars", so that the XML looks like this:

<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>

Is it possible to use Newtonsoft Json.NET? Thanks for any help!

+4
source share
1 answer

DeserializeXmlNode() JSON XML. , , JSON, XML, XML .

, , Json.Net LINQ-to-JSON API XML JSON . :

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

+1

All Articles