How to convert XML to Dictionary

后端 未结 3 918
孤独总比滥情好
孤独总比滥情好 2021-01-03 23:42

I\'ve xml as following:



  Log In
  

        
相关标签:
3条回答
  • 2021-01-04 00:10
    var xdoc = XDocument.Load(path_to_xml);
    _dictionary = xdoc.Descendants("data")
                      .ToDictionary(d => (string)d.Attribute("name"),
                                    d => (string)d);
    
    0 讨论(0)
  • 2021-01-04 00:15

    This is an old question, but in case someone comes across a 'Typed' xml (e.g from a SharedPreference file of an android app), you can handle it as below: Here is a sample of such an xml I took from an Instagram app.

    <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
    <map>
    <boolean name="pinnable_stickers" value="false" />
    <string name="phone_number">+254711339900</string>
    <int name="score" value="0" />
    <string name="subscription_list">[]</string>
    <long name="last_address_book_updated_timestamp" value="1499326818875" />
     //...other properties
    </map>
    

    Note the inconsistency in the value property. Some fields(e.g of type string) don't have it explicitly defined.

    var elements = XElement.Load(filePath)
    .Elements()
    .ToList();
    var dict = new Dictionary<string, string>();    
    var _dict = elements.ToDictionary(key => key.Attribute("name").Value,
                            val => val.Attribute("value") != null ?
                            val.Attribute("value").Value : val.Value);
    
    0 讨论(0)
  • 2021-01-04 00:22
    XDocument xdoc = XDocument.Load("test.XML");
    var query = xdoc.Descendants("root")
                    .Elements()
                    .ToDictionary(r => r.Attribute("name").Value,
                                 r => r.Value);
    

    Remeber to include :

    using System.Linq;
    using System.Xml.Linq;
    
    0 讨论(0)
提交回复
热议问题