By default, the namespace when creating an XML document

Is it possible to create children using XmlDocument.CreateElement () and XmlNode.AppendChild () without specifying a namespace and using this default namespace?

Currently, if I create a root node with a namespace and do not specify a namespace for each child node, the XML output address will define an empty namespace.

The following is what is generated if I do not specify a namespace for each element created. Is there a shortcut where I don't need to specify a namespace every time?

<root xmlns="http://example.com">
  <child1 xmlns="">
    <child2 />
  </child1>
</root>

the 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);
+3
source share
2 answers

XML- - - :

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

:

<root xmlns="http://www.example.com">
  <child1>
    <child2 />
  </child1>
</root>

<root> node , - .

XmlElement doc.CreateElement, XML, , , , , XML, .

, , , - , - , .

+8

.NET 3.5, LINQ to XML (System.Xml.Linq). XDocument, XElement XAttribute.

marc_s , .

+2

Source: https://habr.com/ru/post/1749970/


All Articles