Reading XML to a Dictionary

MasterMastic picture MasterMastic · Jul 5, 2011 · Viewed 13k times · Source

I need to read an XML file to a dictionary.

I read few guides and I only got confused from weird words that I don't understand (such as nodes, XML validation etc.). So, could you please walk me through?

I have an XML file which is written in this format:

<database>
    <def number="1" name="one"/>
    <def number="2" name="two"/>
</database>

As mentioned, I want to store it in a dictionary. How would I go about that?

Answer

Marc Gravell picture Marc Gravell · Jul 5, 2011
var data = XElement.Parse(xml)
    .Elements("def")
    .ToDictionary(
        el => (int)el.Attribute("number"),
        el => (string)el.Attribute("name")
    );

This:

  • parses the xml into an XElement (starting at <database>)
  • iterates over the <def ...> elements
  • forms a dictionary, using @number as the key (interpreting as an int), and @name as the value (as a string)
  • assigns this dictionary to data, which is implicitly typed as Dictionary<int,string>