Linq to XML parse a node into dictionary

I can't figure this one out myself. My XML file looks like this:

<section name="blah">
   <setting1 name="blah">blah</setting1>
   <setting1 name="blah1">blah1</setting1>
</section>

<section name="foo">
   <setting2 name="sth">sth</setting2>
   <setting2 name="sth1">lala</setting2>
</section>

And so on.

What I would like to do is parse each section into it's own individual Dictionary, like this:

Dictionary <string, string> foo;
Dictionary <string, string> blah;

XElement xelement = XElement.Load("test.xml");
IEnumerable<XElement> sections = xelement.Elements();
foreach (var section in sections)
{
    switch (section.Attribute("name").Value)
    {
        case "foo":
            foo = ... Something
            break;

        case "blah":
            blah = ... Something
            break;
    }
}

And so on.

After parsing:

foo["sth1"] <---- contains lala
blah["blah1"] <---- contains blah1

How can I achieve this in Linq?

Jon Skeet
people
quotationmark

While you could hard-code the names as variables, I suspect you'd be better off with a Dictionary<string, Dictionary<string, string>>:

var settings = element.Elements("section")
     .ToDictionary(section => section.Attribute("name").Value,
                   section => section.Elements()
                       .ToDictionary(setting => setting.Attribute("name)".Value,
                                     setting => setting.Value));

Console.WriteLine(settings["foo"]["sth1"]); // lala

This uses a nested call to ToDictionary, where you specify the key and the value given any particular item. The value of each element of the outer dictionary is itself a dictionary, created from the elements within the section.

people

See more on this question at Stackoverflow