Jonatan
Jonatan

Reputation: 110

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.

Upvotes: 2

Views: 1448

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

Just add all of your desired namespaces as attributes to root element, like

root.SetAttribute("xmlns:ns2", "http://example.com/ns2");

Adding this single line at the end will produce almost exactly your desired output (the only difference is order of xmlns attributes, but I think it doesn't matter in your case):

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

Upvotes: 2

Related Questions