Skip to main content
 首页 » 编程设计

c#之如何使用 LINQ to XML 将节点放入字典中

2024年02月23日15shihaiming

这是我的 XML 文件:

<Root> 
    <Level1> 
        <Foo ID="1" Count="20" /> 
        <Foo ID="2" Count="28" /> 
        <Foo ID="3" Count="25" /> 
    </Level1> 
</Root> 

我的 XML 中只有一个 1 级元素,其中有几个 Foo 节点。

如何在字典中获取 Foo 节点?
我是说 Dictionary<int, int> .

请您参考如下方法:

var doc = XDocument.Load(fileName); 
var dictionary = 
    doc.Root 
        .Element("Level1") 
        .Elements("Foo") 
        .ToDictionary( 
            e => (int)e.Attribute("Id"), 
            e => (int)e.Attribute("Count"));