tags:

views:

367

answers:

3

I'm using LINQ together with XDocument to read a XML File. This is the code:

XDocument xml = XDocument.Load(filename);

var q = from b in xml.Descendants("product")
        select new
        {
            name = b.Element("name").Value,
            price = b.Element("price").Value,                    
            extra = b.Element("extra1").Value,
            deeplink = b.Element("deepLink").Value                   
        };

Now the problem is, the extra1 field is not always present. There are items in the XML file without that node. If that happens it's crashing with a NullReferenceException.

Is there any possibility to include a "check if null" so I can prevent it from crashing?

+6  A: 

Use (string) instead of .Value:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name"),
            price = (double?)b.Element("price"),                    
            extra = (string)b.Element("extra1"),
            deeplink = (string)b.Element("deepLink")                   
        };

This also works with other datatypes, including many nullable types in case the element is not always present.

dtb
+1 - interesting.
womp
A: 

You should be able to use the conditional operator as well.

b.Element("extra1") != null ? b.Element("extra").Value : string.Empty
Anthony Pegram
A: 

You can use "null coalescing" operator:

var q = from b in xml.Descendants("product")
        select new
        {
            name = (string)b.Element("name") ?? "Default Name",
            price = (double?)b.Element("price") ?? 0.0,                    
            extra = (string)b.Element("extra1") ?? String.Empty,
            deeplink = (string)b.Element("deepLink") ?? String.Empty                   
        };

This way, you will have full control about default value used when there's no element.

Marqus
`price` needs to be `double?` for that line to make sense.
AakashM