0

I wanted to convert the JSON data into XML contains the JSON array entries into the same. JSON data which I am converting is as below

{
   "userName":[
      "user1",
      "user2"
   ],
   "referenceNumber":"098784866589157763",
   "responseCode":"00",
   "responseDesc":"Success."
}

To convert the JSON to XML using below C# code

XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonData, "response");

which is converting JSON to below XML

<response>
    <userName>user1</userName>
    <userName>user2</userName>
    <referenceNumber>098784866589157763</referenceNumber>
    <responseCode>00</responseCode>
    <responseDesc>Success.</responseDesc>
</response>

but expected output XML is as below

<response>
    <userName>
        <element>user1</element>
        <element>user2</element>
    </userName>
    <referenceNumber>098784866589157763</referenceNumber>
    <responseCode>00</responseCode>
    <responseDesc>Success.</responseDesc>
</response>

Is there any way to achieve the same?

1
  • 2
    You have to transform it manually. please avoid using the extremely dated System.Xml.XmlDocument family of APIs and use the modern System.Xml.Linq.XDocument apis that will save you many headaches as you implement your transformation. Commented Jun 15, 2020 at 6:22

1 Answer 1

1

If you can use the LINQ to XML, which is elegant way to manipulate XML documents, then below is one of the ways to achieve the requirement:

   XElement root = JsonConvert.DeserializeXNode(jsonData, "response").Root;

       // Create elements for userName in new XML
   var docFinal = new XDocument(new XElement("response" , new XElement("userName",            
                  from user in root.Descendants("userName") select new XElement("element", user.Value))));

        //Add remaining XML Attributs
   docFinal.Root.Add(root.Elements()
                   .Select(x => new XElement(x.Name, x.Value)).Where(x => x.Name != "userName"));

        //OUTPUT 
        //<response>
        //  <userName>
        //    <element>user1</element>
        //    <element>user2</element>
        //  </userName>
        //  <referenceNumber>098784866589157763</referenceNumber>
        //  <responseCode>00</responseCode>
        //  <responseDesc>Success.</responseDesc>
        //</response>
Sign up to request clarification or add additional context in comments.

1 Comment

Just use JsonConvert.DeserializeXNode(jsonData, "response").Root not XElement.Parse(JsonConvert.DeserializeXmlNode(jsonData, "response").InnerXml) -- you're deserializing to an XmlDocument then formatting and parsing again to an XDocument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.