C # Download Dictionary from XML

I have an XML file that looks like this:

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

I want to load city information into a dictionary so that my dictionary looks like this:

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

The following code works:

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 it one step.

Any suggestions?

+5
source share
4 answers

Why is it so complicated? Here's how you could do it in the method chain syntax:

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

or just like a simple old loop if you need to use an older version of C # or want to keep things out of date:

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

Try using ToDictionary.

    Dictionary<string, string> allItems = rootNodes.ToDictionary(v => v.Name, v => v.Value);
+5
source

Use either. In this example, you must ensure that the TagName is converted to a string.

Dictionary<string, string> allItems = (from n in rootNodes
select new
            {
                TagName = n.Name,
                TagValue = n.Value
            }).ToDictionary(v => v.TagName.ToString(), v => v.TagValue);

Or save XName as a key

Dictionary<XName, string> allItems = (from n in rootNodes
select new
            {
                TagName = n.Name,
                TagValue = n.Value
            }).ToDictionary(v => v.TagName, v => v.TagValue);
0
source
var element = xmlDoc.Root.Element("Cities");
            if (element != null)
            {
                var idList = element.Descendants().Where(p_ => p_.Name == "Name").Select(v_ => v_.Value).ToArray();
                var valList = element.Descendants().Where(p_ => p_.Name == "Population").Select(v_ => v_.Value).ToArray();

                var citiesDictionary = idList.Zip(valList, (key_, value_) => new { k = key_, v = value_ }).ToDictionary(x_ => x_.k, x_ => x_.v);
0
source

All Articles