.net – How to remove xmlns attribute with .NET XML API

.netapixmlxml-namespaces

XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:

XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>";
doc.DocumentElement.Attributes.RemoveNamedItem("attr2");
Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]);
doc.DocumentElement.Attributes.RemoveNamedItem("xmlns");
Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]);

The resulting output is

xmlns attr before removal=System.Xml.XmlAttribute
xmlns attr after removal=
<Element1 attr1="value1" xmlns="http://mynamespace.com/" />

The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml.
I guess it is because of the special meaning of this attribute.

The question is how to remove the xmlns attribute using .NET XML API.
Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.

@Edit: I'm talking about .NET 2.0.

Best Solution

.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original "namespaced" document to a new one in which the elements will be not namespace-qualified.