Home > Back-end >  Convert Xml to Json with Attribute Id
Convert Xml to Json with Attribute Id

Time:10-16

I have an xml. I want to convert this document to a JSON file like below. How can I do that?

My XML part:

<?xml version="1.0" encoding="UTF-8"?>
<AdditionalFields>
   <AdditionalField id="Token">Tr3stdGf9Nf7zPJBPzwiv1</AdditionalField>
   <AdditionalField id="OrderId">10449-1371587</AdditionalField>
   <AdditionalField id="Code">0190</AdditionalField>
   <AdditionalField id="TxnNumber">279</AdditionalField>
   <AdditionalField id="TranslationID" />
</AdditionalFields>


My Expected Json:

{
  "AdditionalFields": {
      "Token": "Tr3stdGf9Nf7zPJBPzwiv1",
      "OrderId": "10449-1371587",
      "Code": "0190",
      "TxnNumber": "279",
      "TranslationID": ""
   }
}

CodePudding user response:

you have to convert xml to a json object, after this the raw json object convert to the one you like

    using Newtonsoft.Json;

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(xml);
    XmlNode node = xmlDoc.SelectSingleNode("AdditionalFields");


    var jsonArr = JObject.Parse(JsonConvert.SerializeXmlNode(node))["AdditionalFields"]["AdditionalField"];

    var jsonObj = new JObject() { ["AdditionalFields"] = new JObject() };
    var additionalFields = (JObject)jsonObj["AdditionalFields"];

    foreach (JObject jObj in jsonArr)
    {
        var props = jObj.Properties().ToArray();
        if (props.Length == 2)
            additionalFields.Add((string)props[0].Value, props[1].Value);
        else additionalFields.Add((string)props[0].Value, string.Empty);
    }

    var json = jsonObj.ToString();

CodePudding user response:

There are several ways to convert xml to json. Most of the times I think that you don't need to reinvent the wheel. What I mean is that you can use tools on the internet that allow you to convert xml to json. Here's some recommendations:

On the other hand, if you need to do it programmatically, I would re-visit the comment from above.

That's my take. Hope it helps you.

  • Related