How to: Check for nulls when using LINQ to XML
Posted
Wednesday, February 6, 2008 4:54 PM
by
CoreyRoth
I continue to work with LINQ to XML, and I thought this might be worth mentioning (although it is somewhat common sense). An issue often when working with XML attribute (or elements) is that they might not always exists (i.e.: they are null). Therefore, you need to check for this. Specifically, this is an issue when you are assigning attributes into a new anonymous type (although it could occur using a regular type as well). Consider the following example. What if MyColumn is not present in some of the Item elements in the XML document? The code would end up throwing an exception when you tried to enumerate items.
var items = from item in assetTypes.Elements("Item") select new
{
Name = item.Attribute("Name").Value,
MyColumn = item.Attribute("MyColumn").Value
};
How do you fix it? First you use the Any() method of the attribute to see if any of that attribute exist. Then it is just a matter of using shorthand if/then syntax. Just replace MyColumn with the code below.
MyColumn = item.Attributes("MyColumn").Any() ? item.Attribute("MyColumn") : null
As you can see it is relatively simple, once you know to use Any() to look for the existance of an attribute. On a related note you can apply the same techique to see if an element exists.