Converting XmlDocument to Dictionary

后端 未结 3 1455
长发绾君心
长发绾君心 2021-01-16 09:54

I\'m looking for a good way to convert an XmlDocument to Dictionary using Linq.

My xml is formatted like this:

<
相关标签:
3条回答
  • 2021-01-16 10:42

    I dont know if its the better way, but its clean & simple..

    XElement xdoc = XElement.Load("yourFilePath");
    Dictionary<string, string> result = (from element in xdoc.Elements() select new KeyValuePair<string, string>(element.Name.ToString(), element.Value)).ToDictionary(x => x.Key, x => x.Value);
    
    0 讨论(0)
  • 2021-01-16 10:42

    Using an XmlDocument, per your question, you can use this approach to get a Dictionary<string, string>.

    string input = @"<config>
        <field>value</field>
        <field2>value2</field2>
    </config>";
    
    var xml = new XmlDocument();
    xml.LoadXml(input);
    
    var dict = xml.SelectNodes("/config/*")
                  .Cast<XmlNode>()
                  .ToDictionary(n => n.Name, n => n.InnerText);
    

    If you can use an XElement, you can use either the Parse method to load the XML from a string, or use the Load method to load it from a file. Then this approach should suffice:

    var xml = XElement.Parse(input);
    var dict = xml.Elements()
                  .ToDictionary(n => n.Name.LocalName, n => n.Value);
    
    0 讨论(0)
  • 2021-01-16 10:44

    One way of doing it with linq would be the following Create an XML document using

    XElement xDoc = XElement.Parse("<config><field>value</field><field2>value2</field2</config>");
    

    For simplicity, I inlined your XML snippet into the parse directly.

    Then you can create a query with the following

    var query = from xEle in xDoc.Descendants()
    select new { tag = xEle.Name.LocalName, value = xEle.Value };
    

    Then convert that query to a dictionary using a simple for each loop.

    Dictionary<string, string> dictionary = new Dictionary<string, string>();
    foreach (var CurNode in query)
    {
        dictionary.Add(CurNode.tag, CurNode.value);
    }
    
    0 讨论(0)
提交回复
热议问题