Image This is an xml file
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
Is that you expect
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
I think the code below is what you want. You need to put each element in the correct namespace and remove any xmlns = '' attributes for the affected elements. The last part is required, since otherwise LINQ to XML basically tries to leave you with an element
<Firstelement xmlns="" xmlns="http://my.namespace">
Here is the code:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument doc = XDocument.Load("test.xml");
foreach (var node in doc.Root.Descendants())
{
if (node.Name.NamespaceName == "")
{
node.Attributes("xmlns").Remove();
node.Name = node.Parent.Name.Namespace + node.Name.LocalName;
}
}
Console.WriteLine(doc);
}
}