title: Adding Key, Value XML Element using C#
body: <p>I have a problem with adding an element to an XML file using C#. I have my <code>App.config</code> files somewhere in my diff directory. So I am using LINQ to retrieve the values I want and to set the value from TextBoxes.</p>
  
  <pre><code>&lt;appSettings&gt;
      &lt;add key="Something" value="false" /&gt;
      &lt;add key="UserName" value="user0001" /&gt;
      &lt;add key="Password" value="123456" /&gt;
      &lt;add key="Environment" value="" /&gt;
      &lt;add key="DBUserName" value="DBname23" /&gt;
      &lt;add key="DBPassword" value="12345678" /&gt;
  &lt;/appSettings&gt;
  </code></pre>
  
  <p>The above is my XML file. I am able to retrieve the values of <code>UserName</code> and <code>Password</code> and set it with the encrypted ones. The way I am doing is shown below:</p>
  
  <pre><code>var doc1 = XDocument.Load(appConfigFile1);
  
  var list1 = from appNode in doc1.Descendants("appSettings").Elements()
              where appNode.Attribute("key").Value == "UserName"
              select appNode;
  var list2 = from appNode in doc1.Descendants("appSettings").Elements()
              where appNode.Attribute("key").Value == "Password"
              select appNode;
  var list3 = from appNode in doc1.Descendants("appSettings").Elements()
              where appNode.Attribute("key").Value == "DBUserName"
              select appNode;
  var list4 = from appNode in doc1.Descendants("appSettings").Elements()
              where appNode.Attribute("key").Value == "DBPassword"
              select appNode;
  var element1 = list1.FirstOrDefault();
  var element2 = list2.FirstOrDefault();
  var element3 = list3.FirstOrDefault();
  var element4 = list4.FirstOrDefault();
  element1.Attribute("value").SetValue(txtbox1);
  element2.Attribute("value").SetValue(txtbox2);
  element3.Attribute("value").SetValue(txtbox3);
  element4.Attribute("value").SetValue(txtbox4);
  doc1.Save(appConfigFile1);
  </code></pre>
  
  <p>The requirements are such that if one of the elements from the XML file is deleted, I should be able to create a same element with key and value.</p>
  
  <p>Example: Please compare the above xml with the below:</p>
  
  <pre><code>&lt;appSettings&gt;
      &lt;add key="HasUI" value="false" /&gt;
      &lt;add key="Password" value="123456" /&gt;
      &lt;add key="Environment" value="" /&gt;
      &lt;add key="DBUserName" value="DBname23" /&gt;
      &lt;add key="DBPassword" value="12345678" /&gt;
  &lt;/appSettings&gt;
  </code></pre>
  
  <p>Above the element Username is missing. So how can I create an XML element like
       <code>&lt;add key="UserName" value="" /&gt;</code> and set that to that same place in XML file?</p>
  
  <p>The error I am getting when I load the XML file in C# is NullReferenceException.</p>
  
  <p>Please help me.</p>