How to convert XML to Dictionary

Ramzy Abourafeh picture Ramzy Abourafeh · Dec 19, 2012 · Viewed 14k times · Source

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();
}

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Dec 19, 2012
var xdoc = XDocument.Load(path_to_xml);
_dictionary = xdoc.Descendants("data")
                  .ToDictionary(d => (string)d.Attribute("name"),
                                d => (string)d);