简体   繁体   中英

LINQ to XML: Project to a List<string>

Using LINQ to XML, how can I project the following XML data into a List<string> with the values "Test1", "Test2" and "Test3".

<objectlist>
    <object code="Test1" />
    <object code="Test2" />
    <object code="Test3" />
</objectlist>

I have the XML available in a string:

XDocument xlist = XDocument.Parse(xmlData);

Thanks

var query = from node in xlist.Root.Elements("object")
            select node.Attribute("code").Value

var result = query.ToList();

Or, with extension method syntax:

var query = xlist.Root.Elements("object")
               .Select(node => node.Attribute("code").Value)
               .ToList()
var xDoc = XDocument.Parse(xml);
List<string> codes = xDoc.Descendants("object")
                        .Select(o => o.Attribute("code").Value)
                        .ToList();

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