Linq / XML - How do you handle non-existent nodes?

I am trying to figure out how to handle nodes that do not exist for all my card elements. I have the following linq request:

    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 element, I read another post that ??? processes zero. I get the following error:

The operator '??' cannot be applied to operands of type 'int' and 'int'

How do I solve this problem?

Thank!

+3
source share
1 answer

Instead of using the property Valuecast to string... and for int, instead int?. User-defined conversions to nullable types return null if source XAttribute/ XElementis null:

FinalDeck = (from deck in xmlDoc.Root.Element("Cards")
                .Elements("Card")
                select new CardDeck
                {
                    Name = (string) deck.Attribute("name"),
                    Image = (string) deck.Element("Image").Attribute("path"),
                    Usage = (int?) deck.Element("Usage"),
                    Type = (string) deck.Element("Type"),
                    Strength = (int?) deck.Element("Ability") ?? 0
                }).ToList();  

, , Image , , path. , , , .

EDIT: :

public static XAttribute NullSafeAttribute(this XElement element, XName name)
{
    return element == null ? null : element.Attribute(name);
}

:

Image = (string) deck.Element("Image").NullSafeAttribute("path"),
+4

All Articles