XDocument or XmlDocument for JSON from C #
I have this XML which is wonderful:
<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 don't want my json to have no "Product" level because all three lines are 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 an XmlDocument and use:
var xmlDocument = new System.Xml.XmlDocument();
using (var xmlReader = x.CreateReader())
{
xmlDocument.Load(xmlReader);
}
JsonConvert.SerializeXmNode(xmlDocument);
This gives me exactly the same result. So how can I change my JSON parsing so that I have a simple list of products. I prefer the cleanest solution.
To be a little more clear, I would like to do this as a result:
[{"@ProductCode":"C1010","@CategoryName":"Coins"},
{"@ProductCode":"C1012","@CategoryName":"Coins"},
{"@ProductCode":"C1013","@CategoryName":"Coins"}]
+3
source to share
3 answers
Getting started with xml writer or con version. Just read from the original XML file an entry in a new file using the file stream writer.
basically you would:
List xml_retrevedData = new List();
FileStramWriter fr = new FileStramWriter();
fr.Write("{"Products":[{"@ProductCode":" //colection item
variable1.data1","@CategoryName":"//colection item
variable1.data2"}, {"@ProductCode":"//colection item
variable2.data1","@CategoryName":"//colection item
variable11.data1"},
{"@ProductCode":"//colection item variable13.data1","@CategoryName":"//colection item variable13.data3"}]}");
// in side the file stream Writer
0
source to share
try it
public string getData(ref XmlDocument doc) {
JObject productobj = new JObject();
var productsenum = from p in doc.GetElementsByTagName("product").Cast<XmlElement>()
select p;
JArray products = new JArray();
foreach (XmlElement p in productsenum) {
JObject pobj = new JObject();
pobj["ProductCode"] = p.GetAttribute("ProductCode");
pobj["CategoryName"]= p.GetAttribute("CategoryName");
products.Add(pobj);
}
JObject product = new JObject();
product["Product"] = products;
productobj["Products"] = product;
return productobj.ToString();
}
0
source to share