C#,XML:将第二个命名空间移动到根元素

C#, XML: move second namespace to root element

我正在尝试创建一个 XML 文档,使用 System.XML.XmlDocument Class.

我的文档中有两个命名空间。

我的 C# 代码是什么样的:

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

期望的输出:

<?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>

实际输出:

<?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>

因为第二个命名空间的元素在我的文档中多次出现,我不想重复声明第二个命名空间,而是只在根元素中声明一次。

我怎样才能做到这一点?

我不适合使用 LINQ2XML。

只需将您想要的所有名称空间作为属性添加到根元素,例如

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

在末尾添加这一行将几乎完全产生您想要的输出(唯一的区别是 xmlns 属性的顺序,但我认为这对您的情况无关紧要):

<?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>