的XDocument或XmlDocument的用C#为JSON [英] XDocument or XmlDocument to JSON with C#

查看:457
本文介绍了的XDocument或XmlDocument的用C#为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的XML这是伟大的:

 <产品> 
<产品的产品代码=C1010类别名称=钱币/>
<产品的产品代码=C1012类别名称=钱币/>
<产品的产品代码=C1013类别名称=钱币/>
< /产品>



但它输出到这个JSON:

  {产品:{产品:[{@产品代码:C1010,@类别名称:钱币},
{@ProductCode :C1012,@类别名称:钱币},
{@ProductCode:C1013,@类别名称:硬币}]}}

我想在我的JSON无产品分段,因为所有的三根线的产品。这是我的C#代码:

  // x是一个XDocument。 
JsonConvert.SerializeXNode(X,Formatting.None,FALSE)
//JsonConvert.SerializeXNode(x); //我也试过没有格式化和布尔。

当我将'一个XDocument到的XmlDocument和使用:

  VAR XMLDOCUMENT =新System.Xml.XmlDocument();使用
(VAR的XMLReader = x.CreateReader())
{
XMLDocument.load方法(XMLReader的);
}
JsonConvert.SerializeXmNode(XmlDocument的);



这让我完全一样的输出。那么,如何可以修改我的JSON解析,这样我的产品的一个简单的列表。我喜欢干净的解决方案



要成为也许有点更清晰,我会像这样的输出:

  [{@产品代码:C1010,@类别名称:钱币},
{@ProductCode:C1012,@类别名称:钱币},
{@ProductCode:C1013,@类别名称:硬币}]


解决方案

使用方法调用

  JsonConvert。 SerializeXNode(X,Formatting.None,真正的); 

这将省去根节点,并应创造你所期望的。


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"}]

解决方案

Use the method call

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

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

这篇关于的XDocument或XmlDocument的用C#为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆