I'm trying to convert an xml feed to linq, but I'm having trouble checking if an element is null or not before retrieving that element's data. I was convinced my following code is correct, but one of the xml's rows is missing the element "ElementOne" and it's child "Element", so it's throwing the whole script when executed.
This snippet is incomplete but this is the part that's causing the whole script to error, can anyone spot why this would error?
from c in s.Element("ElementOne").Elements("ElementTwo")
where s.Element("ElementOne") != null &&
s.Element("ElementOne").Elements("ElementTwo") != null
select new{
Id = (c.Attribute("Id") == null) ? 0 : (int)c.Attribute("Id")
}
I would just change it to:
var query = s.Elements("ElementOne").Elements("ElementTwo")
.Select(c => (int?) c.Attribute("Id") ?? 0);
(Unless you really need the anonymous type, why bother with it?)
If there are no ElementOne
elements, this will just give you an empty result.
If you want to only use the first ElementOne
element even if there are multiple ones, you can use:
var query = s.Elements("ElementOne").Take(1).Elements("ElementTwo")
.Select(c => (int?) c.Attribute("Id") ?? 0);
See more on this question at Stackoverflow