Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

To be perhaps a bit more clear, I'd something like this as output:

[{"@ProductCode":"C1010","@CategoryName":"Coins"},
{"@ProductCode":"C1012","@CategoryName":"Coins"},     
{"@ProductCode":"C1013","@CategoryName":"Coins"}]
like image 513
JP Hellemons Avatar asked Mar 16 '26 11:03

JP Hellemons


1 Answers

Use the method call

JsonConvert.SerializeXNode(x, Formatting.None, true);

this will omit the root node and should create what you expect.

like image 141
Jehof Avatar answered Mar 18 '26 23:03

Jehof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!