in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, MOSS 2007, ASP.NET, LINQ, and Visual Studio 2012.

How to: Check for nulls when using LINQ to XML

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.

Published Feb 06 2008, 04:54 PM by CoreyRoth
Filed under:

Comments

 

Mithun said:

Perfect, your was the only site that I found had to the point solution to this problem! Took me hours to find it but eventually got there :-) Cheers - Mithun

June 1, 2010 12:15 PM
 

Ramesh said:

Excellent work. Thanks lot for your help.

August 17, 2011 12:06 AM
 

Office 365 の技術系ブログ said:

対象: Office 365 for Enterprise Grid には、重要な情報を持つ Office 365 の専門家が多数含まれています。 Grid のユーザー投稿ブログ シリーズ

March 12, 2012 4:10 PM

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an Applications Architect at Infusion specializing in ECM and Search.
2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems