Reading XML using XDocument & Linq - check if element is NULL? Reading XML using XDocument & Linq - check if element is NULL? xml xml

Reading XML using XDocument & Linq - check if element is NULL?


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.


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.


Use the following example for checking existence of any element before using that element.

if( b.Elements("extra1").Any() ){   extra = b.Element("extra1").Value;}