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
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?
CodePudding user response:
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"
}
}
CodePudding user response:
With XQuery 3.1, this is
declare option output:method "json";
declare option output:indent "yes";
map{"Summary":
map{"status": xs:boolean(//Summary/status),
"etc": string(//Summary/etc)
}
}
Using XSLT or XQuery for XML-to-json conversion gives you complete control over the mapping, you're not subject the whims of the designer of some conversion library. Standard conversion libraries rarely give you enough control to do the whole job without some pre- or post-processing.