我有一个很棒的XML:
<Products>
<Product ProductCode="C1010" CategoryName="Coins" />
<Product ProductCode="C1012" CategoryName="Coins" />
<Product ProductCode="C1013" CategoryName="Coins" />
</Products>
但是它输出到这个JSON:
{"Products":{"Product":[{"@ProductCode":"C1010","@CategoryName":"Coins"},
{"@ProductCode":"C1012","@CategoryName":"Coins"},
{"@ProductCode":"C1013","@CategoryName":"Coins"}]}}
我希望json中没有"Product"子级别,因为这三行都是一个产品。这是我的C#代码:
//x is an XDocument.
JsonConvert.SerializeXNode(x, Formatting.None, false)
//JsonConvert.SerializeXNode(x); //I also tried without the formatting and the boolean.
当我将XDocument"转换"为XmlDocument并使用:时
var xmlDocument = new System.Xml.XmlDocument();
using (var xmlReader = x.CreateReader())
{
xmlDocument.Load(xmlReader);
}
JsonConvert.SerializeXmNode(xmlDocument);
它给了我完全相同的输出。那么,我如何修改JSON解析,以便获得一个简单的产品列表呢。我更喜欢最干净的溶液。
为了更清楚一点,我想要这样的输出:
[{"@ProductCode":"C1010","@CategoryName":"Coins"},
{"@ProductCode":"C1012","@CategoryName":"Coins"},
{"@ProductCode":"C1013","@CategoryName":"Coins"}]
使用方法调用
JsonConvert.SerializeXNode(x, Formatting.None, true);
这将省略根节点,并且应该创建您期望的内容。
使用xml编写器或con版本的说明只需从原始xml文件中读取一个新文件中的写入即可使用文件流编写器。
基本上你会是:
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
尝试这个
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();
}