How to convert XML to JSON using C#/LINQ?

前端 未结 3 1133
感情败类
感情败类 2020-11-30 01:52

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

3条回答
  •  盖世英雄少女心
    2020-11-30 02:26

    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.

提交回复
热议问题