c# – 将JSON数组转换为XML
发布时间:2020-12-15 22:28:37 所属栏目:百科 来源:网络整理
导读:我正在尝试将 JSON转换为XML.我的 JSON包含一系列汽车,每辆汽车都有一系列功能: [ { "car": { "features": [{ "code": "1" },{ "code": "2" }] } },{ "car": { "features": [{ "code": "3" },{ "code": "2" }] } }] 我正在将其转换为XML: // the tag name
我正在尝试将
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |