How to prevent blank xmlns attributes in output from .NET's XmlDocument? How to prevent blank xmlns attributes in output from .NET's XmlDocument? xml xml

How to prevent blank xmlns attributes in output from .NET's XmlDocument?


Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank xmlns attributes: pass in the root node's namespace when creating any child node you want not to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to also not have prefixes.

Fixed Code:

XmlDocument xml = new XmlDocument();xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); Console.WriteLine(xml.OuterXml);

Thanks everyone to all your answers which led me in the right direction!


This is a variant of JeniT's answer (Thank you very very much btw!)

XmlElement new_element = doc.CreateElement("Foo", doc.DocumentElement.NamespaceURI);

This eliminates having to copy or repeat the namespace everywhere.


If the <loner> element in your sample XML didn't have the xmlns default namespace declaration on it, then it would be in the whatever:name-space-1.0 namespace rather than being in no namespace. If that's what you want, you need to create the element in that namespace:

xml.CreateElement("loner", "whatever:name-space-1.0")

If you want the <loner> element to be in no namespace, then the XML that's been produced is exactly what you need, and you shouldn't worry about the xmlns attribute that's been added automatically for you.