2010-04-26 67 views
1

给出下面的XML结构:如何使用Linq从XML创建一个字典数组?

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

我怎么能创建词典的阵列,使得每个字典包含课程中的所有元素/值对?

我现在所拥有的生成数组,其元素包含单个键/值字典用于在过程的每个元素/值对:

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

产地:

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

I”什么D类似于是这样的:

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

回答

4

像这样:

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

-1:不编译。 – 2010-04-26 14:51:19

+0

现在它编译。 – SLaks 2010-04-26 14:53:02

+0

Visual Studio抱怨'System.Xml.Linq.XElement'不包含ToDictionary()的定义。 – Matt 2010-04-26 14:54:19