I have a piece of XML that looks like
<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>
When I try to serialize it to json string json = JsonConvert.SerializeXmlNode(xml);
it ignores namespaces
{
"person": {
"@id": "1",
"name": "Alan",
"url": "http://www.google.com",
"role": [
"Admin"
]
}
}
and when I deserialize it back to xml XmlDocument xml = JsonConvert.DeserializeXmlNode(json)
, I get the following:
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role>Admin</role>
</person>
How can I keep the json:Array
attributes?
There is overload of DeserializeXmlNode
which accepts boolean flag named writeArrayAttribute
. That's what you need:
XmlDocument xml = JsonConvert.DeserializeXmlNode(json, null, true);
Produces:
<person id="1">
<name>Alan</name>
<url>http://www.google.com</url>
<role xmlns:json="http://james.newtonking.com/projects/json" json:Array="true">Admin</role>
</person>
Which is semantically identical to original xml.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With