C# Load Dictionary from XML

c#, linq-to-xml, xml

Solution

Why so complex? Here is how you could do it in method chain syntax:

var allItems = rootNodes.ToDictionary(n => n.Name.ToString(), n => n.Value);

or just as a plain old loop, if you need to use an older version of C# or would like to keep things old-fashioned:

var allItems = new Dictionary<string, string>();
foreach (var node in rootNodes)
{
    allItems.Add(node.Name.ToString(), node.Value);
}

Problem

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?

Original source