微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将JSON数组转换为XML

我正在尝试将 JSON转换为XML.我的 JSON包含一系列汽车,每辆汽车都有一系列功能

[
    {
        "car": {
            "features": [{
                "code": "1"
            },{
                "code": "2"
            }]
        }
    },{
        "car": {
            "features": [{
                "code": "3"
            },{
                "code": "2"
            }]
        }
    }
]

我正在将其转换为XML:

// the tag name for each top level element in the json array
var wrappedDocument = string.Format("{{ car: {0} }}",jsonResult);
// set the root tag name
return JsonConvert.DeserializeXmlNode(wrappedDocument,"cars");

这是生成的XML:

<cars>
   <car>
      <features>
        <code>1</code>
      </features>
      <features>
        <code>2</code>
      </features>
   </car>
   <car>
      <features>
        <code>3</code>
      </features>
      <features>
        <code>2</code>
      </features>
   </car>
</cars>

我的问题是,我希望将所有“功能”列在公共元素下,就像“汽车”一样列在“汽车”下,这样XML就像这样:

<cars>
   <car>
       <features>
          <feature>
            <code>1</code>
          </feature>
          <feature>
            <code>2</code>
          </feature>
        </features>
   </car>
   <car>
       <features>
          <feature>
            <code>3</code>
          </feature>
          <feature>
            <code>2</code>
          </feature>
        </features>
   </car>
</cars>

可以使用Newtonsoft Json.NET吗?感谢您的任何帮助!

解决方法

DeserializeXmlNode()实际上没有办法自定义JSON到XML转换的方式.要使用该方法获得所需的结果,您必须在将JSON转换为XML之前对其进行操作,或者之后操作XML.

在这种情况下,我认为使用Json.Net的LINQ-to-JSON API直接从JSON以您想要的形状构建XML可能更容易.你可以这样做:

var ja = JArray.Parse(jsonResult);
var xml = new XDocument(
    new XElement("cars",ja.Select(c => 
            new XElement("car",new XElement("features",c["car"]["features"].Select(f => 
                        new XElement("feature",new XElement("code",(string)f["code"])
                        )
                    )
                )
            )
        )
    )
);

Console.WriteLine(xml.ToString());

小提琴:https://dotnetfiddle.net/fxxQnL

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐