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/