When generating XML from XmlDocument in .NET, a blank xmlns
attribute appears the first time an element without an associated namespace is inserted; how can this be prevented?
Example:
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
Output:
<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
Desired Output:
<root xmlns="whatever:name-space-1.0"><loner /></root>
Is there a solution applicable to the XmlDocument
code, not something that occurs after converting the document to a string with OuterXml
?
My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank xmlns
attribute may not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.
Since root is in an unprefixed namespace, any child of root that wants to be un-namespaced has to be output like your example. The solution would be to prefix the root element like so:
code:
I've solved the problem by using the Factory Pattern. I created a factory for XElement objects. As parameter for the instantiation of the factory I've specified a XNamespace object. So, everytime a XElement is created by the factory the namespace will be added automatically. Here is the code of the factory:
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:
Thanks everyone to all your answers which led me in the right direction!
Yes you can prevent the XMLNS from the XmlElement . First Creating time it is coming : like that
Change the code : And pass xml namespace like this
C# code:
If possible, create a serialization class then do:
It's safer, and you can control the namespaces with attributes if you really need more control.
This is a variant of JeniT's answer (Thank you very very much btw!)
This eliminates having to copy or repeat the namespace everywhere.