C#, XML: move second namespace to root element



I am trying to create an XML document, using the System.XML.XmlDocument Class.


I have two namespaces in my document.


What my C# code looks like:



XmlDocument xDoc = new XmlDocument();
xDoc.InsertBefore(xDoc.CreateXmlDeclaration("1.0","UTF-8","yes"),xDoc.DocumentElement);
XmlElement root = xDoc.CreateElement('ROOT','http://example.org/ns1');
xDoc.AppendChild(root);
XmlElement child1 = xDoc.CreateElement('CHILD1','http://example.org/ns1');
root.AppendChild(child1);
XmlElement child2 = xDoc.CreateElement('ns2:CHILD2','http://example.com/ns2');
root.AppendChild(child2);
XmlElement child3 = xDoc.CreateElement('ns2:CHILD3','http://example.com/ns2');
root.AppendChild(child3);


Desired output:



<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<ROOT xmlns="http://example.org/ns1" xmlns:ns2="http://example.com/ns2">
<CHILD1/>
<ns2:CHILD2/>
<ns2:CHILD3/>
</ROOT>


Actual output:



<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<ROOT xmlns="http://example.org/ns1">
<CHILD1/>
<ns2:CHILD2 xmlns:ns2="http://example.com/ns2"/>
<ns2:CHILD3 xmlns:ns2="http://example.com/ns2"/>
</ROOT>


Because elements of the second namespace occur multiple times in my document, I don't want this repetitive declaration of the second namespace, but instead have it only once in the root element.


How can I achieve that?


Using LINQ2XML is not an option for me.


No comments:

Post a Comment