如何在 XDocument 中添加命名空间和声明

How to add Namespace and Declaration in XDocument

我正在用 C# 创建 xml,并希望添加命名空间和声明。我的 xml 如下:

XNamespace ns = "http://ab.com//abc";

XDocument myXML = new XDocument(
    new XDeclaration("1.0","utf-8","yes"),
    new XElement(ns + "Root",
        new XElement("abc","1")))

这将在根级别和子元素 abc 级别添加 xmlns=""

<Root xmlns="http://ab.com/ab">
    <abc xmlns=""></abc>
</Root>

但我只希望在根级别而不是子级别,如下所示:

<Root xmlns="http://ab.com/ab">
    <abc></abc>
</Root>

以及如何在顶部添加声明,我的代码在 运行 之后不显示声明。

请帮助我获得完整的 xml 作为

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Root xmlns="http://ab.com/ab">
    <abc></abc>
</Root>

您需要在子元素中使用相同的命名空间:

XDocument myXML = new XDocument(
    new XDeclaration("1.0","utf-8","yes"),
        new XElement(ns + "Root",
            new XElement(ns + "abc", "1")))

如果您只使用 "abc",这将被转换为没有命名空间的 XName。然后这会导致添加 xmlns="" 属性,因此 abc 的完全限定元素名称将被解析为这样。

通过将名称设置为 ns + "abc",在转换为字符串时不会添加 xmlns 属性,因为 http://ab.com/ab 的默认命名空间继承自 Root

如果您只想 'inherit' 命名空间,那么您将无法以如此流畅的方式执行此操作。您将使用父元素的名称空间创建 XName,例如:

 var root = new XElement(ns + "Root");
 root.Add(new XElement(root.Name.Namespace + "abc", "1"));

关于声明,XDocument在调用ToString时不包括这个。如果您使用 Save 写入 StreamTextWriter,或者如果您提供的 XmlWriter 在其 [= 中没有 OmitXmlDeclaration = true 28=].

如果您只想获取字符串,this question 有一个使用 StringWriter.

的漂亮扩展方法的答案

在您创建的所有元素上使用命名空间:

XDocument myXML = new XDocument(
                  new XDeclaration("1.0","utf-8","yes"),
                  new XElement(ns + "Root",
                     new XElement(ns + "abc","1")))