Thursday, February 22, 2018

Keep json:Array attribute when converting XML to JSON to XML

Leave a Comment

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?

3 Answers

Answers 1

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.

Answers 2

The XMl to JSon loses all the information of any attributes that have ':' (colon) in their name. Which is why 'id' get serialised to @id but 'xmlns:json' is lost in translation.

If you have access to the raw XML then I will suggest you replace the colons(:) by hyphens(-). In this case, the XML will be:

<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> 

I have checked that this serialises and de-serialises to the same input and output.

var xmlString = @"<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>"; var xml = new XmlDocument(); xml.LoadXml(xmlString);  var json = JsonConvert.SerializeXmlNode(xml);  var xmlDeserialized = JsonConvert.DeserializeXmlNode(json); xmlDeserialized.Should().NotBeNull(); xmlDeserialized.ShouldBeEquivalentTo(xml); //All good 

Answers 3

Maybe the problem is not how you serialize the xml node. Verify how you read your xml file before serializing it. Can you show us?

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment