title: NullException XML Parsing
body: <p>I'm having a problem with parsing XML in C#, my XML file looks like this:</p>
  
  <pre><code>&lt;xml&gt;
      &lt;category&gt;books&lt;/category&gt;
      &lt;id&gt;1&lt;/id&gt;
      &lt;title&gt;lemony&lt;/title&gt;
      &lt;sub&gt;
          &lt;title&gt;lemonyauthor&lt;/title&gt;
      &lt;/sub&gt;
  &lt;/xml&gt;
  &lt;xml&gt;
      &lt;category&gt;comics&lt;/category&gt;
      &lt;id&gt;2&lt;/id&gt;
      &lt;sub&gt;
          &lt;title&gt;okauthor&lt;/title&gt;
      &lt;/sub&gt;
  &lt;/xml&gt;
  </code></pre>
  
  <p>As you can see sometimes the title in "XML" is returned, sometimes not.</p>
  
  <p>My code in C# to parse this looks like:</p>
  
  <pre><code>string _Title;
  
  foreach (XElement str in xmlDoc.Descendants("xml"))
  {
      _Title = "";
  
          if (str.Element("title").Value != null)
              _Title = str.Element("title").Value;
  
          foreach (XElement cha in str.Descendants("sub"))
          {
              if (_Title.Length &lt; 1 &amp;&amp; cha.Element("Title").Value != null)
                      _Title = cha.Element("title").Value;
          }
  }
  </code></pre>
  
  <p>How do I keep the line <code>if (str.Element("category").Value != null)</code> from returning a <code>NullException</code>?</p>
  
  <p>Is using <code>try</code> &amp; <code>catch</code> the only way?</p>