1

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.

EZLearner
  • 1,614
  • 16
  • 25

1 Answers1

6

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.

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
Rob G
  • 3,496
  • 1
  • 20
  • 29