user9993
user9993

Reputation: 6170

Populating a Dictionary with LINQ to XML

I am using LINQ to XML to parse an XML document and create a number of objects from that XML. One of the objects has a Dictionary as a property and I need to populate the Dictionary from the XML. However, I am unsure of the actual syntax required to do so.

I know that I need to get the attribute values and somehow assign them to the key/value in the dictionary.

How do I do this?

I have a model class like this:

public class Statistics
{
    string Name { get; set; }
    public IDictionary<string, string> Information { get; set; }
}

And XML like this:

  <section>
    <parameter name="this is a key" value="this is a value" />
    <parameter name="this is a key 2" value="this is a value 2" />
  </section>

In my LINQ query I need to set the key and value from the name and value attributes.

From my understanding I need to do something along the lines of:

.ToDictionary(x => x.name, x => x.value);

But I am unsure how to apply that to my LINQ query, the following code is a part of a larger LINQ to XML query:

.Select(x => new Statistics
                {
                    Name = x.Attribute("name").Value,
                    Information = What goes here? .Select.Attributes? .ToDictionary(x => x.name, x => x.value);

Upvotes: 0

Views: 1203

Answers (2)

Pomme De Terre
Pomme De Terre

Reputation: 372

I don't think it's the best solution.

I would do something like that :

.Select(x => new Statistics
            {
                Name = x.Attribute("name").Value,
                Information = GetParameterDictionnary(sectionNode)

and I would create the function

private Dictionary<string, string> GetParameterDictionnary(XmlNode sectionNode)
{
    var dictionary = new Dictionary<string,string>();
    foreach(var child in sectionNode.Children)
    {
        dictionary.Add(child.Attribute("name"), child.Attribute("value"));
    }
    return dictionary;
}

Upvotes: 1

Eser
Eser

Reputation: 12546

var dict = XDocument.Load(filename)
           .Descendants("parameter")
           .ToDictionary(p => p.Attribute("name").Value, p => p.Attribute("value").Value);

Upvotes: 3

Related Questions