How to cause a JSON property to be converted to XML as an attribute of an xml-element

感情迁移 提交于 2019-12-08 08:52:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!