我正在尝试使用 System.XML.XmlDocument 类创建 XML 文档。
我的文档中有两个命名空间。
我的 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>
关于C#、XML : move second namespace to root element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28835708/