Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert XML to JSON without attributes?

I have the following XML as string and need to convert it to JSON:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope>
   <SOAP-ENV:Body>
      <Results>
         <Summary>
            <Status xsi:type="xsd:boolean">true</Status>
            <etc xsi:type="xsd:string">etc</etc>
         </Summary>
      </Results>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

My expected output is:

{
  "Summary": {
    "Status": true,
    "etc": "etc"
  }
}

My attempt

I am using the following code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var doc = new XmlDocument();
doc.LoadXml(xmlString);
var json = JsonConvert.SerializeXmlNode(doc);
var jObject = JObject.Parse(json);
var final = Convert.ToString(jObject["SOAP-ENV:Envelope"]["SOAP-ENV:Body"]["Results"]["Summary"]);

However, this results in a weird JSON like the following:

{
  "Status": {
    "@xsi:type": "xsd:boolean",
    "#text": "true"
  },
  "etc": {
    "@xsi:type": "xsd:string",
    "#text": "etc"
  },
}

What should I do?

SerializeXmlNode

>Solution :

You can parse it with XDocument. XDocument can remove attributes.

public static XDocument RemoveAttributes(string xml)
{
    var xDoc = XDocument.Parse(xml);

    xDoc.Document?
        .Descendants()
        .ForEach(x => {

            foreach (var attr in x.Attributes().ToList())
            {
                if (attr.IsNamespaceDeclaration)
                    continue;

                attr.Remove();
            }
        }
    );
    return xDoc;
}

var xDoc = RemoveAttributes(xmlString);

var json = JsonConvert.SerializeXNode(xDoc);
var jObject = JObject.Parse(json);
var final = Convert.ToString(jObject["SOAP-ENV:Envelope"]["SOAP-ENV:Body"]["Results"]);

Result is:

{
  "Summary": {
    "Status": "true",
    "etc": "etc"
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading