I’m working with an existing XML document which has a structure (in part) like so:
<Group> <Entry> <Name> Bob </Name> <ID> 1 </ID> </Entry> <Entry> <Name> Larry </Name> </Entry> </Group>
I’m using LINQ to XML to query the XDocument to retrieve all these entries as follows:
var items = from g in xDocument.Root.Descendants('Group').Elements('Entry') select new { name = (string)g.element('Name').Value, id = g.Elements('ID').Count() > 0 ? (string)g.Element('ID').Value : 'none' };
The ‘ID’ elements aren’t always there and so my solution to this was the Count() jazz above. But I’m wondering if someone has a better way to do this. I’m still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I’m currently doing it.
Is there a better/more preferred way to do what I want?
XElement actually has interesting explicit conversion operators that do the right thing in this case.
So, you rarely actually need to access the
.Valueproperty.This is all you need for your projection:
And if you’d prefer to use the value of
IDas an integer in your anonymous type: