c# - 如何将 xml 字符串转换为字典列表?

标签 c# xml

string xml="< theme>

<colors>

<color>
<code>1</code>
<name>blue</name>
<priority>5</priority>
</color>

<color>
<code>2</code>
<name>red</name>
<priority>2</priority>
</color>

<color>
<code>3</code>
<name>green</name>
<priority>7</priority>
</color>

</colors>
</theme>"

我想将此 xml 字符串转换为名为“颜色”的字典列表。例如:

List< Dictionary< string, string>> colors=new List< Dictionary< string, string>>();   
colors=//Magic happens here  

colors[0]["name"] would return 'blue'  
colors[2]["priority"] would return '7'  

等等

谢谢。

最佳答案

假设您使用的是 LINQ to XML,这相对容易:

var query = doc.Descendants("colors")
               .Elements() // Get to each "color" element
               .Select(outer => outer.Elements()
                                     .ToDictionary(x => x.Name.LocalName,
                                                   x => x.Value))
               .ToList();

如果其中任何一个对您来说没有意义,请告诉我。

编辑:糟糕,那本来是一个 List<Dictionary<XName, string>>前。固定 :)

编辑:我在您的评论中注意到您使用的是完全限定名称。尝试使用这些 using 指令:

using System.Linq;
using System.Xml.Linq;

他们需要找到扩展方法。

关于c# - 如何将 xml 字符串转换为字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3651181/

相关文章:

c# - 为 C# 互操作对象创建可重用的 Excel 样式

java - Android 在 Activity 中保留 Nav Bar

jquery - 通过 OpenERP-7 中的特定按钮以只读模式打开表单

Java:XML 对象

c# - MessageDialog 在 Windows Phone 8.1 上用 3 个命令中断

c# - LINQ 查询性能低下

java - 解析格式错误的 XML 文档(如 HTML 文件)

java - 使用适用于 android 的 SIMPLE XML 库将不同命名的元素解析为单个列表

c# - nuget 包安装生成的空数据上下文

c# - 在 Azure Blob 存储中使用 Etag 进行乐观锁定不起作用