I am trying to figure out how to handle nodes that do not exist for all of my “card” elements. I have the following linq query:
FinalDeck = (from deck in xmlDoc.Root.Element("Cards")
.Elements("Card")
select new CardDeck
{
Name = deck.Attribute("name").Value,
Image = deck.Element("Image").Attribute("path").Value,
Usage = (int)deck.Element("Usage"),
Type = deck.Element("Type").Value,
Strength = (int)deck.Element("Ability") ?? 0
}).ToList();
with the Strength item, I had read another posting that the ?? handles the null. I am getting the following error though:
Operator ‘??’ cannot be applied to operands of type ‘int’ and ‘int’
How do I handle this issue?
Thanks!
Rather than use the
Valueproperty, cast tostring… and for theint, cast toint?instead. The user defined conversions to nullable types will return null if the sourceXAttribute/XElementis null:Note that this won’t help for the case where the
Imageelement is missing, as then it’ll try to dereference a null element to find thepathattribute. Let me know if you want a workaround for that, but it’ll be a bit of a pain, relatively speaking.EDIT: You can always create an extension method for this yourself:
Then call it like this: