C# Load Dictionary from XML

Viewed 12831

I have an XML file that looks like:

<Cities>
    <Name>Seattle</Name>
    <State>WA</State>
    <Population>552105</Population>
</Cities>

I want to load the city info into a dictionary, so that my dictionary looks like:

cityDictionary("Name") = "Seattle"
cityDictionary("State") = "WA"
cityDictionary("Population") = "552105"

The following code does work:

var doc = XDocument.Load(@"..\..\Cities.xml");
var rootNodes = doc.Root.DescendantNodes().OfType<XElement>();
var keyValuePairs = from n in rootNodes
                    select new
                    {
                        TagName = n.Name,
                        TagValue = n.Value
                    };

Dicitionary<string, string> allItems = new Dictionary<string, string>();
foreach (var token in keyValuePairs) {
    allItems.Add(token.TagName.ToString(), token.TagValue.ToString());
}

But I want to do this one step.

Any suggestions?

4 Answers
Related