views:

87

answers:

1

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]}
+4  A: 

Like this:

x.Elements("course")
 .Select(c => c.Elements().ToDictionary(y => y.Name, y => y.Value))
 .ToArray();
SLaks
-1: Doesn't compile.
Cameron MacFarland
Now it does compile.
SLaks
Visual Studio complains that 'System.Xml.Linq.XElement' does not contain a definition for ToDictionary().
Duke
Yes; I already fixed that.
SLaks
The result is the same as the undesired structure illustrated in my question - an array of single-entry dictionaries.
Duke
I tried it, and I got an array of double-entry dictionaries.
SLaks
Whoops, you're right. I was misinterpreting how the VS debugger displayed the data structure. Thank you!
Duke