title: How to fix 'System.NullReferenceException: 'Object reference not set to an instance of an object.'
body: <p>I am new to Xml and Linq and I have been following a tutorial on youtube on how to use it.</p>
  
  <p>Link to the video: <a href="https://www.youtube.com/watch?v=OsfVJ485RY4" rel="nofollow noreferrer">https://www.youtube.com/watch?v=OsfVJ485RY4</a></p>
  
  <p>The problem is that when I run the code to either change the value or delete it, I always get the following error:</p>
  
  <pre><code>System.NullReferenceException: 'Object reference not set to an instance of an object.'
  
  System.Xml.Linq.XElement.Attribute(...) returned null.
  </code></pre>
  
  <p><strong>First of all I load my document:</strong></p>
  
  <pre><code>XDocument xmlDocument = XDocument.Load(@"C:\Users\matpl\source\repos\LinqToXML\LinqToXML\Data.xml");
  </code></pre>
  
  <p><strong>The part where I want to change the value of the Xml document</strong></p>
  
  <pre><code>xmlDocument.Element("Students")
             .Elements("Student")
             .Where(x =&gt; x.Attribute("Id").Value == "101").FirstOrDefault()
             .SetElementValue("TotalMarks", "999");
  </code></pre>
  
  <p><strong>When I want to delete an element:</strong></p>
  
  <pre><code>xmlDocument.Root.Elements().Where(x =&gt; x.Attribute("Id").Value == "104").Remove();
  </code></pre>
  
  <p><strong>XML file:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8" standalone="yes"?&gt;
  &lt;!--Comment Updated--&gt;
  &lt;Students&gt;
    &lt;Student&gt;
      &lt;Student Id='101'&gt;
        &lt;Name&gt;Mark&lt;/Name&gt;
        &lt;Gender&gt;Male&lt;/Gender&gt;
        &lt;TotalMarks&gt;800&lt;/TotalMarks&gt;
      &lt;/Student&gt;
      &lt;Student Id='102'&gt;
        &lt;Name&gt;Rosy&lt;/Name&gt;
        &lt;Gender&gt;Female&lt;/Gender&gt;
        &lt;TotalMarks&gt;900&lt;/TotalMarks&gt;
      &lt;/Student&gt;
      &lt;Student Id='103'&gt;
        &lt;Name&gt;Pam&lt;/Name&gt;
        &lt;Gender&gt;Female&lt;/Gender&gt;
        &lt;TotalMarks&gt;850&lt;/TotalMarks&gt;
      &lt;/Student&gt;
      &lt;Student Id='104'&gt;
        &lt;Name&gt;John&lt;/Name&gt;
        &lt;Gender&gt;Male&lt;/Gender&gt;
        &lt;TotalMarks&gt;950&lt;/TotalMarks&gt;
      &lt;/Student&gt;
    &lt;/Student&gt;
    &lt;Student Id='105'&gt;
      &lt;Name&gt;Todd&lt;/Name&gt;
      &lt;Gender&gt;Male&lt;/Gender&gt;
      &lt;TotalMarks&gt;980&lt;/TotalMarks&gt;
    &lt;/Student&gt;
  &lt;/Students&gt;
  </code></pre>
  
  <p>Thank you,</p>