Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 247
user7518s Avatar asked Feb 04 '23 01:02

user7518s


1 Answers

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.

like image 182
Evk Avatar answered Feb 20 '23 21:02

Evk