问题
Using Newtonsoft's .Net Library to convert JSON to XML, is there a way to convert a specific JSON element to an XML attribute?
For example, taking the following JSON:
{
"array": {
"item": [
1,
2,
3
],
"length": 3
}
}
and converting it to:
<array length="3">
<item>1</item>
<item>2</item>
<item>3</item>
</array>
Thanks.
回答1:
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.
looks like: "@length": "3",
for a definition of an attribute called 'length'
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; }
}
Then use your Json serializer to deserialize into it, and then use an Xml serializer to serialize the JsonToXmlTranslationObject
into your XML.
来源:https://stackoverflow.com/questions/18293965/how-to-cause-a-json-property-to-be-converted-to-xml-as-an-attribute-of-an-xml-el