Monday, 8 December 2014

Is there a way of preventing duplicate XML nodes when converting Json to XML?



I am using JsonConvert to deserialise a Json object to XML but because the Json has a different structure for elements at the same level I am getting duplicate nodes in my resulting XML.


My Json looks like this:



{
"shipments": [
{
"id": "A000001",
"name": "20141208 140652",
"type": "OUTLET",
"date": "2014-12-08 14:06:52",
"status": "SENT",
"received_at": null,
"created_at": "2014-12-08 14:06:52",
"updated_at": null,
"outlet_id": "SH000064",
},
{
"id": "A000002",
"name": "20141204 122650",
"type": "SUPPLIER",
"date": "2014-12-04 12:26:50",
"outlet_id": "SH000064",
"supplier_id": null,
"status": "RECEIVED",
"received_at": "2014-12-04 12:28:43",
"created_at": "2014-12-04 12:26:50",
"updated_at": "2014-12-04 12:28:43",
},
]
}


After conversion the XML looks like this:



<root>
<shipments>
<id>A000001</id>
<name>20141208 140652</name>
<type>OUTLET</type>
<date>2014-12-08 14:06:52</date>
<status>SENT</status>
<received_at />
<created_at>2014-12-08 14:06:52</created_at>
<updated_at />
<outlet_id>SH000064</outlet_id>
</shipments>
<shipments>
<id>A000002</id>
<name>20141204 122650</name>
<type>SUPPLIER</type>
<date>2014-12-04 12:26:50</date>
<outlet_id>SH000064</outlet_id>
<supplier_id />
<status>RECEIVED</status>
<received_at>2014-12-04 12:28:43</received_at>
<created_at>2014-12-04 12:26:50</created_at>
<updated_at>2014-12-04 12:28:43</updated_at>
<outlet_id>SH000064</outlet_id>
</shipments>
</root>


The code I'm using to convert the Json is:



var document = JsonConvert.DeserializeXmlNode(json, "root");
var xml = document.OuterXml;


The problem is the duplication of the outlet_id node in the second shipments element. The input Json passes validation so I assume this is a common problem. Is there a way around it?


No comments:

Post a Comment