Dave New
Dave New

Reputation: 40002

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

Upvotes: 1

Views: 641

Answers (2)

jeroenh
jeroenh

Reputation: 26772

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()

Upvotes: 2

L.B
L.B

Reputation: 116098

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

Upvotes: 1

Related Questions