如何将JSON属性转换为XML作为xml-element的属性 [英] How to cause a JSON property to be converted to XML as an attribute of an xml-element
问题描述
使用Newtonsoft的.Net库将JSON转换为XML,是否可以将特定的JSON元素转换为XML属性?
Using Newtonsoft's .Net Library to convert JSON to XML, is there a way to convert a specific JSON element to an XML attribute?
例如,采用以下JSON:
For example, taking the following JSON:
{
"array": {
"item": [
1,
2,
3
],
"length": 3
}
}
并将其转换为:
<array length="3">
<item>1</item>
<item>2</item>
<item>3</item>
</array>
谢谢.
推荐答案
可以在属性前面加上@并将其放在对象的顶部吗?它在文档中说:
Can you prefix the attributes with @ and put them at the top of the object? It says in the docs:
属性以@开头,应位于的开头. 对象.
Attributes are prefixed with an @ and should be at the start of the object.
看起来像:"@length": "3",
用于定义名为长度"的属性
looks like: "@length": "3",
for a definition of an attribute called 'length'
或者,您可以将JSON反序列化为对象,然后将其重新序列化为Xml:
Alternatively you could deserialize your JSON into an object and then reserializing it as Xml:
[XmlRoot(ElementName="array")]
class JsonToXmlTranslationObject {
[XmlElement(ElementName="item")]
public int[] item { get; set; }
[XmlAttribute]
public int length { get; set; }
}
然后使用您的Json序列化器将其反序列化,然后使用Xml序列化器将JsonToXmlTranslationObject
序列化为XML.
Then use your Json serializer to deserialize into it, and then use an Xml serializer to serialize the JsonToXmlTranslationObject
into your XML.
这篇关于如何将JSON属性转换为XML作为xml-element的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!