Matt
Matt

Reputation: 1059

How can I use Linq to create an array of dictionaries from XML?

Given the following XML structure:

<courses>
  <course>
    <title>foo</title>
    <description>bar</description>
  </course>
  ...
</courses>

How could I create an array of dictionaries such that each dictionary contains all the element/value pairs within a course?

What I have right now generates an array whose elements contain a single key/value dictionary for each element/value pair in a course:

XElement x = XElement.Parse("...xml string...");
var foo = (from n in x.Elements() select n)
    .Elements().ToDictionary(y => y.Name, y => y.Value);

Produces:

[0] => {[course, foo]}
[1] => {[description, bar]}

What I'd like is this:

[0] => {[course, foo], [description, bar]}

Upvotes: 1

Views: 408

Answers (1)

SLaks
SLaks

Reputation: 887657

Like this:

x.Elements("course")
 .Select(c => c.Elements().ToDictionary(y => y.Name, y => y.Value))
 .ToArray();

Upvotes: 4

Related Questions