3

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);
0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Erm, marc_s's answer doesn't say the namespace is inherited. It says you have to manually specify it for every XML element you create.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.