title: How can I replace xmlns namespace attributes with prefixes?
body: <p>I have been trying to write a utility in C# which takes an XML file, removes the xmlns attributes from the tags, sets the prefix of these attributes in the root tag, and then uses these prefixes in the tags instead.</p>
  
  <p><strong>Source XML file:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;Main version="1.0" xmlns="urn:root:v1"&gt;
      &lt;Report&gt;
          &lt;Title&gt;Some Value&lt;/Title&gt;
      &lt;/Report&gt;
      &lt;Content&gt;
          &lt;Address&gt;
              &lt;CountryName xmlns="urn:location:v2"&gt;Australia&lt;/CountryName&gt;
          &lt;/Address&gt;
      &lt;/Content&gt;
  &lt;/Main&gt;
  </code></pre>
  
  <p><strong>Target XML file:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;root:Main version="1.0" xmlns:root="urn:root:v1" xmlns:loc="urn:location:v2"&gt;
      &lt;root:Report&gt;
          &lt;root:Title&gt;Some Value&lt;/root:Title&gt;
      &lt;/root:Report&gt;
      &lt;root:Content&gt;
          &lt;root:Address&gt;
              &lt;loc:CountryName&gt;Australia&lt;/loc:CountryName&gt;
          &lt;/root:Address&gt;
      &lt;/root:Content&gt;
  &lt;/root:Main&gt;
  </code></pre>
  
  <p>I've managed to get part of the way there with the following code.  I have replaced all tags with no attributes with the root prefix, and added the xmlns attribute to the root tag, but have not been successful with removing the xmlns attribute from CountryName tag and using the prefix there instead.</p>
  
  <pre><code>XDocument doc = XDocument.Load(@"C:\Temp\Source.xml");
  
  var content = XElement.Parse(doc.ToString());
  
  content.Attributes("xmlns").Remove();
  
  content.Add(new XAttribute(XNamespace.Xmlns + "root", "urn:root:v1"));
  content.Add(new XAttribute(XNamespace.Xmlns + "loc", "urn:location:v2"));
  
  foreach (var node in doc.Root.Descendants().Where(n =&gt; n.Name.NamespaceName == "urn:location:v2"))
  {
      node.Attribute("xmlns").Remove();
      node.Add(new XAttribute(XNamespace.Xmlns + "loc", "urn:location:v2"));
  }   
  
  content.Save(@"C:\Temp\Target.xml");
  </code></pre>
  
  <p>Any help would be appreciated - thanks!</p>