简体   繁体   中英

How to put a node in a dictionary using LINQ to XML

This is the XML file which I have:

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

I only have one Level 1 element in my XML, and inside of it there several Foo nodes.

How can I get that Foo nodes in a dictionary?
I mean 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"));

XElement.Parse("XML here").Descendants("Foo").Select( s => s).ToDictionary( x=> x.Attribute("ID").Value, x=> x.Attribute("Count").Value))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM