2010-04-26 106 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