XDocument or XmlDocument to JSON with C#



I have this XML which is great:



<Products>
<Product ProductCode="C1010" CategoryName="Coins" />
<Product ProductCode="C1012" CategoryName="Coins" />
<Product ProductCode="C1013" CategoryName="Coins" />
</Products>


but it outputs to this JSON:



{"Products":{"Product":[{"@ProductCode":"C1010","@CategoryName":"Coins"},
{"@ProductCode":"C1012","@CategoryName":"Coins"},
{"@ProductCode":"C1013","@CategoryName":"Coins"}]}}


I would like no 'Product' sublevel in my json because all three lines are a product. This is my C# code:



//x is an XDocument.
JsonConvert.SerializeXNode(x, Formatting.None, false)
//JsonConvert.SerializeXNode(x); //I also tried without the formatting and the boolean.


When I 'convert' an XDocument to XmlDocument and use:



var xmlDocument = new System.Xml.XmlDocument();
using (var xmlReader = x.CreateReader())
{
xmlDocument.Load(xmlReader);
}
JsonConvert.SerializeXmNode(xmlDocument);


It gives me exactly the same output. So how can I modify my JSON parsing such that I have a simple list of products. I prefer the cleanest solution.


No comments:

Post a Comment