Nested XML to Dictionary

前端 未结 4 1091
既然无缘
既然无缘 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条回答
  •  一个人的身影
    2021-01-25 04:06

    Here is a method which will distill the data into tuples and then output a dictionary. Note it doesn't check for duplicate keys, but that could be added:

    string data = @"
    
      val1
      val2
      
        param1
        paramval1
      
      
        param2
        paramval2
      
    ";
    
    var elements = XDocument.Parse( data )
                            .Element("Root")
                            .Descendants();
    
    var asTupleChildren =  elements.Where (e => e.HasElements)
                                   .Select (e => new Tuple(e.Element("ParameterName").Value, e.Element("ParameterValue").Value ));
    
    var asTupleElements =  elements.Where (e => e.HasElements == false)
                                   .Where (e => e.Name != "ParameterName" && e.Name != "ParameterValue" )
                                   .Select (e => new Tuple(e.Name.ToString(), e.Value ));
    
    
    var asDictionary =  asTupleElements.Concat(asTupleChildren)
                                       .ToDictionary (te => te.Item1, te => te.Item2);
    
    
    /* asDictionary is a Dictionary (4 items)
    
    a1 val1
    a2 val2
    param1 paramval1
    param2 paramval2
    
    */
    

提交回复
热议问题