Is it possible to create children using XmlDocument.CreateElement() and XmlNode.AppendChild() without specifying the namespace and have it use a “default” namespace?
Currently, if I create a root node with a namespace and don’t specify the namespace on the every childnode, the output xml will define a blank namespace.
Below is what is generated if I don’t specify the namespace for every element I create. Is there a shortcut where I don’t have to specify the namespace every time?
<root xmlns="http://example.com">
<child1 xmlns="">
<child2 />
</child1>
</root>
Code:
XmlDocument doc = new XmlDocument();
var rootNode = doc.CreateElement("root", "http://example.com");
doc.AppendChild(rootNode);
var child1Node = doc.CreateElement("child1");
rootNode.AppendChild(child1Node);
var child2Node = doc.CreateElement("child2");
child1Node.AppendChild(child2Node);
If you have create your XML document, and you specify the same namespace for each element in the hierarchy – something like this:
then you’ll get this output file:
The namespace on the
<root>node is inherited down the hierarchy, unless the child elements define something else explicitly.If you create a new XmlElement using
doc.CreateElementand you don’t specify a XML namespace, then of course, that new element, will have a blank namespace and thus this will be serialized into that XML document you had.I am not aware of any way to specify a default namespace to use whenever you’re creating a new element – if you specify one, the element will use that namespace – if you don’t specify one, it’s the blank namespace.