Skip to main content
 首页 » 编程设计

c#之如何使用 Linq 从 XML 创建字典数组

2024年02月24日24TianFang

给定以下 XML 结构:

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

我如何创建一个字典数组,使每个字典都包含类(class)中的所有元素/值对?

我现在所拥有的生成一个数组,其元素包含类(class)中每个元素/值对的单个键/值字典:

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]} 

我想要的是:

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

请您参考如下方法:

像这样:

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