强制将根xml元素转换为json转换中的数组 [英] Force root xml element to be array on json conversion
问题描述
我在下面使用( http://james.newtonking.com/projects/json)强制XML节点在转换为JSON时成为数组:
I am using below (http://james.newtonking.com/projects/json) to force XML nodes to be an array when converted to JSON:
<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>
我得到的是
{
"person": {
"@id": "1",
"name": "Alan",
"url": "http://www.google.com",
"role": [
"Admin"
]
}
}
我想要的是
{
"person": [
{
"@id": "1",
"name": "Alan",
"url": "http://www.google.com",
"role": [
"Admin"
]
}
]
}
是否可以在根节点上强制使用数组?
Is it possible to force array on root node ?
推荐答案
我能够通过以下方式获得您想要的结果:
I am able to get the result you desire by:
-
将
json:Array='true'
添加到根元素<person>
.
由于您已经将该属性添加到<role>
中,因此也不必将其添加到根元素中.
Since you are already adding this attribute to <role>
adding it to the root element as well should not be a burden.
将XML加载到XDocument
(或XmlDocument
)中并转换文档本身,而不只是转换根元素XDocument.Root
.
Loading the XML into an XDocument
(or XmlDocument
) and converting the document itself rather than just the root element XDocument.Root
.
因此:
var xml = @"<person xmlns:json='http://james.newtonking.com/projects/json' id='1' json:Array='true'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>";
var xDocument = XDocument.Parse(xml);
var json1 = JsonConvert.SerializeXNode(xDocument, Newtonsoft.Json.Formatting.Indented);
生成所需的JSON:
{
"person": [
{
"@id": "1",
"name": "Alan",
"url": "http://www.google.com",
"role": [
"Admin"
]
}
]
}
但是以下内容却没有:
var json2 = JsonConvert.SerializeXNode(xDocument.Root, Newtonsoft.Json.Formatting.Indented);
使用XmlDocument
可获得类似的结果,其中只有以下内容可根据需要进行工作:
A similar result obtains using XmlDocument
, in which only the following works as desired:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
var json1 = JsonConvert.SerializeXmlNode(xmlDocument, Newtonsoft.Json.Formatting.Indented);
我在Json.NET 10.0.1和Json.NET 12.0.1上都确认了这一点.为什么序列化文档及其根元素会有所不同,您可能会创建一个 询问Newtonsoft为何如此重要.
I confirmed this on both Json.NET 10.0.1 and Json.NET 12.0.1. It's a bit mysterious why serializing the document vs. its root element should make a difference, you might create an issue for Newtonsoft asking why it should matter.
演示小提琴此处.
这篇关于强制将根xml元素转换为json转换中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!