Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Load Dictionary from XML

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?

like image 802
coson Avatar asked Aug 14 '12 15:08

coson


1 Answers

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);
}
like image 93
Adam Avatar answered Sep 22 '22 20:09

Adam