Convert XML to Json Array when only one object Convert XML to Json Array when only one object xml xml

Convert XML to Json Array when only one object


Read this documentation about Serialize Xml Node

You can force JSON Array this way

var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >             <Item json:Array='true'>                <Name>name</Name>                 <Detail>detail</Detail>                </Item>            </Items>";

DEMO


In case it helps anyone, further to meda's reply.Here's how you make this work with XElement rather than xmlTextWriter and XDocument

XNamespace ns = "http://james.newtonking.com/projects/json";var items = new XElement("items",new XAttribute(XNamespace.Xmlns+"json",ns));   items.Add(new XElement("item",new XAttribute(ns+"Array",true),                        new XElement("name", "name"),                        new XElement("Detail", "detail")));

then to convert it

 XmlDocument doc = new XmlDocument();            doc.LoadXml(items.ToString());            var converted JsonConvert.SerializeXmlNode(doc);


Cinchoo ETL - an open source library available to convert such xml into expected json format

string xml = @"<Items>        <Item>            <Name>name</Name>            <Detail>detail</Detail>            </Item>    </Items>";StringBuilder sb = new StringBuilder();using (var p = ChoXmlReader.LoadText(xml).WithXPath("/")){    using (var w = new ChoJSONWriter(sb)        .Configure(c => c.SupportMultipleContent = true)        )        w.Write(p);}Console.WriteLine(sb.ToString());

Output:

{ "Items": [  {    "Name": "name",    "Detail": "detail"  } ]}

Disclaimer: I'm the author of this library.