title: How do you guard for Null Reference exceptions in Linq To Xml?
body: <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
  &lt;pages&gt; 
    &lt;page id="56"&gt;
      &lt;img id="teaser" src="img/teaser_company.png"&gt;&lt;/img&gt;
    &lt;/page&gt;  
  &lt;/pages&gt;
  </code></pre>
  
  <p>I have an xml file that defines additional resources for pages within a cms. What's the best way to guard for Null Reference exceptions when querying this file with LinqToXml?</p>
  
  <pre><code>var page = (from tabElement in extensionsDoc.Descendants("page")
  where tabElement.Attribute("id").Value == tabId.ToString()
  select tabElement).SingleOrDefault();
  </code></pre>
  
  <p>This code could potentially trigger a Null Reference exception if a page element doesn't have an attribute called "id". Do I have to use a try catch block or is there a way to handle this? For instance return null for page the page object if there's no attribute called "id" for the page element.</p>