Default namespace when created xml document
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开发者_如何学C 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:
XmlDocument doc = new XmlDocument();
const string xmlNS = "http://www.example.com";
XmlElement root = doc.CreateElement("root", xmlNS);
doc.AppendChild(root);
XmlElement child1 = doc.CreateElement("child1", xmlNS);
root.AppendChild(child1);
child1.AppendChild(doc.CreateElement("child2", xmlNS));
doc.Save(@"D:\test.xml");
then you'll get this output file:
<root xmlns="http://www.example.com">
<child1>
<child2 />
</child1>
</root>
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.CreateElement
and 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.
If you are using .NET 3.5, I suggest using LINQ to XML, (System.Xml.Linq). Use the XDocument, XElement, and XAttribute classes.
But marc_s's answer is correct, the namespace is inherited.
精彩评论