C#、XML : move second namespace to root element

标签 c# xml xsd xml-namespaces

我正在尝试使用 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/

相关文章:

c# - 无法加载文件或程序集... Windows Azure 网站

c# - 如果尖括号是我的 URL 中唯一未编码的特殊字符,那么这本身是否危险?

xml - Groovy - XmlSlurper - 将属性读入 map

xml - 使用 XSL 根据 XML 的条件添加命名空间

xml - XPath - 从具有最高节点值的父节点中提取值

c# - 鼠标滚轮输入无法统一识别

c# - 避免 If Else 条件

xml - 使用 SAXParserFactory 的哪种实现?

xml - 如何忽略未知标签的验证?

java - XML 模式在两种不同情况下有两种同名的元素类型