title: How to set attribute value for existing XML element
body: <p>I have an existing XML file and I would like to update some of its attributes. I googled and see many similar questions and answers but I have no luck.</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;system ExportDate="2/15/2018" ExportTime="11:56 AM EST" DateFormat="MM/dd/yyyy" NumberFormat="HH:mm:ss " SchemaValidation="true" ExportVersion="2016.1.SP1710.57 [Build 82] - 27 September 2017 (01:30 IST)" xmlns="http://www.mentor.com/harness/Schema/LibrarySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mentor.com/harness/Schema/LibrarySchema file:/C:/MentorGraphics/VeSys_Client/dtd/LibrarySchema.xsd" XMLVersion="1.6"&gt;
    &lt;librarymaterial librarymaterial_id="XXX" description="YYY" materialcode="ZZZ" /&gt;
   &lt;/system&gt;
  </code></pre>
  
  <p>I am trying to set new values for some of the attributes.<br>
  For the root, I have no issue</p>
  
  <pre><code>xmlDoc.DocumentElement.SetAttribute("ExportDate", DateTime.Now.ToShortDateString());
  xmlDoc.DocumentElement.SetAttribute("ExportTime", DateTime.Now.ToShortTimeString() + " EST");
  </code></pre>
  
  <p>However, when I try the different methods but no hope</p>
  
  <p><strong>Method 1:</strong></p>
  
  <pre><code>XmlNode node = xmlDoc.SelectSingleNode("/system/librarymaterial");
  node.Attributes["librarymaterial_id"].Value=_librarymaterial_id;
  </code></pre>
  
  <p><strong>Error:</strong></p>
  
  <blockquote>
    <p>System.NullReferenceException: 'Object reference not set to an instance of an object.'</p>
  </blockquote>
  
  <p>node was null.</p>
  
  <p><strong>Method 2:</strong></p>
  
  <pre><code>var nodes = xmlDoc.SelectNodes("/system/librarymaterial");
  foreach (XmlElement n in nodes)
  {
      n.SetAttribute("librarymaterial_id", _librarymaterial_id);
  }
  </code></pre>
  
  <p>This does not create an error, but the <code>librarymaterial_id</code> does not get updated. </p>