Reputation: 40002
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
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
Reputation: 116098
var xDoc = XDocument.Parse(xml);
List<string> codes = xDoc.Descendants("object")
.Select(o => o.Attribute("code").Value)
.ToList();
Upvotes: 1