【问题标题】:How can I use Linq to create an array of dictionaries from XML?如何使用 Linq 从 XML 创建字典数组?
【发布时间】:2010-04-26 14:41:11
【问题描述】:

给定以下 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]}

我想要的是这个:

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

【问题讨论】:

    标签: c# xml linq arrays dictionary


    【解决方案1】:

    像这样:

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

    【讨论】:

    • Visual Studio 抱怨“System.Xml.Linq.XElement”不包含 ToDictionary() 的定义。
    • 结果与我的问题中所示的不需要的结构相同 - 单条目字典数组。
    • 我试过了,我得到了一个复式字典数组。
    • 哎呀,你是对的。我误解了 VS 调试器如何显示数据结构。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2019-11-29
    • 2014-09-09
    相关资源
    最近更新 更多