title: Inserting an element into xml produces an unnecessary propertry xmlns=
body: <p>Whenever I insert an element into my xml document, the system adds an xmlns="" attribute to it. How do i get rid of it? Why is it there? Im using very simple linqtoxml.</p>
  
  <p>I've got a simple XML file (Note there is no Xml declaration line and it contains a namespace):</p>
  
  <pre><code>&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"&gt;
    &lt;PropertyGroup&gt;
    &lt;/PropertyGroup&gt;
  &lt;/Project&gt;
  </code></pre>
  
  <p>I do the following:</p>
  
  <pre><code>        //  1. Read in the Xml file
          XDocument testXml = XDocument.Load(@"C:\test.xml");
  
          //  2. Add in the extra node
          XNamespace ns = testXml.Root.Attribute("xmlns").Value;          // Get the existing namespace
          XElement newElement = new XElement("MyNewElement", "12345");    // Create the new element
          testXml.Element( ns + "Project").Add( newElement );          // Insert the new element into the document
  
          //  3. Write To Disk (without the xml header line)
          TextWriter tw = File.CreateText(@"C:\test2.xml");
          tw.Write(testXml.ToString());
          tw.Close();
  </code></pre>
  
  <p>When viewing the file i get:</p>
  
  <pre><code>&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"&gt;
    &lt;PropertyGroup&gt;&lt;/PropertyGroup&gt;
    &lt;MyNewElement xmlns=""&gt;12345&lt;/MyNewElement&gt;
  &lt;/Project&gt;
  </code></pre>
  
  <p>I need to get rid of the xmlns="" bit.
  I believe one needs to include the namespace when adding the new element because the original document has a namespace. I tried to insert the element with :</p>
  
  <pre><code>    testXml.Element( "Project").Add( newElement );
  </code></pre>
  
  <p>but it kept giving me a null referece exception which im assuming it's because the element needs the namespace name.</p>
  
  <p>I thought of parsing it a second time and deleting all the xmlns="" properties, but it doesn't seem to work; I keep getting the null reference exception. There is probably some fundamental understanding of namespaces im lacking here, but ive looked around and cant seem to find any hints.</p>
  
  <p>Can anyone point me in the right direction wth this?</p>
  
  <p>Cheers
  Jack.</p>