Nested XML to Dictionary

前端 未结 4 1121
既然无缘
既然无缘 2021-01-25 03:44

I am trying to convert an XML data into dictionary. I am having problems with identical node names. C# .Net 3.5

Sample XML = the problem is I have no control over this.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 04:02

    How about using DynamicXml here

    dynamic root = DynamicXml.Load("a.xml");
    
    Console.WriteLine(root.a1);
    foreach (var p in root.Parameter)
    {
        Console.WriteLine("{0}:{1}",p.ParameterName, p.ParameterValue);
    }
    Console.WriteLine(root.Parameter[0].ParameterValue);
    

    EDIT

    A generic approach would be to get a dictionary Dictionary But there are some problems while converting an xml to dictionary. For example

    val1
    

    dict["a1"] would return val1, but what would this xml return

    valName
    

    dict["a1"]["name"] ? valAttr or valName?

    And considering your example, the only difference between dict["a1"] and dict["Parameter"] is that Parameter exists more than once under the same parent and it should be thought as an array rather than a single element.

    DynamicXml tries to solve these issues. Of course there is a lot of room for improvement but It should work for basic needs.

提交回复
热议问题