Lasitha Yapa Lasitha Yapa - 1 month ago 8
C# Question

Convert a json text with attributes to xml

I have the following json, which is converted from a XML.

{
"@number":"0",
"Field":[
{
"@key":"status",
"a":"1"
}
]
}


When i use
JsonConvert.DeserializeXmlNode()
function to convert this back to XML it gives me following exception.

System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Converters.XmlDocumentWrapper' to type 'Newtonsoft.Json.Converters.IXmlElement'.


How can I do this?

Answer
var result = JsonConvert.DeserializeXNode(json, "Root");

//output
<Root number="0">
 <Field key="status">
   <a>1</a>
 </Field>
</Root>

This is working without a problem. Be aware that @number and @key will be attributes of specific nodes!