I have the following XML file that I need to convert to JSON in the server. Initially I thought I would convert it to a Dictionary and then use the JavaScriptSerializer to t
For deep nesting of XML elements with more and unknown attributes you can use this recursion:
private static string XmlToJson(string xmlString)
{
return new JavaScriptSerializer().Serialize(GetXmlValues(XElement.Parse(xmlString)));
}
private static Dictionary GetXmlValues(XElement xml)
{
var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlValues(e)));
else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
return new Dictionary { { xml.Name.LocalName, attr } };
}
For your example the result will be:
{
"Columns":{
"_value":[
{
"Column":{
"Name":"key1",
"DataType":"Boolean",
"_value":"True"
}
},
{
"Column":{
"Name":"key2",
"DataType":"String",
"_value":"Hello World"
}
},
{
"Column":{
"Name":"key3",
"DataType":"Integer",
"_value":"999"
}
}
]
}
}
And for more complex XML case like this, you can check the JSON analogue here.