How to convert XML to Dictionary

14,118
var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
                  .ToDictionary(d => (string)d.Attribute("name"),
                                d => (string)d);
Share:
14,118

Related videos on Youtube

Ramzy Abourafeh
Author by

Ramzy Abourafeh

Updated on September 16, 2022

Comments

  • Ramzy Abourafeh
    Ramzy Abourafeh over 1 year

    I've xml as following:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <data name="LogIn">Log In</data>
      <data name="Password">Password</data>
    </root>
    

    I success to do that without Linq, any one can help me to convert the following code to Linq:

    using (XmlReader reader = XmlReader.Create(_xml))
    {
        while (reader.Read())
        {
           if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data")
           {
              reader.MoveToAttribute("name");
              string key = reader.Value;
              reader.MoveToContent();
              string value = reader.ReadElementContentAsString();
              _dictionary.Add(key, value);
           }
        }
        reader.Close();
    }
    
    • Daniel Brückner
      Daniel Brückner over 11 years
      Plain text passwords in an XML file...
  • Ramzy Abourafeh
    Ramzy Abourafeh over 11 years
    I got the following error: 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XEle‌​ment>' does not contain a definition for 'ToDictionary' and no extension method 'ToDictionary' accepting a first argument of type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XEle‌​ment>' could be found (are you missing a using directive or an assembly reference?)
  • ken2k
    ken2k over 11 years
    @RamzyAbourafeh Add using System.Linq; so you can use LINQ extension methods.
  • Habib
    Habib over 11 years
    @lazyberezovsky, what does Descendants("data") do ?
  • Sergey Berezovskiy
    Sergey Berezovskiy over 11 years
    @Habib, it returns descendant elements for this document which have name data msdn - same as xpath //data
  • efkah
    efkah over 11 years
    awesome! @Habib, maybe xdoc.Element("Root").Elements() is better suited for you? but does the same here.
  • Habib
    Habib over 11 years
    @lazyberezovsky, +1 and thanks for the link, and thanks efkah