【问题标题】:How to add Namespace and Declaration in XDocument如何在 XDocument 中添加命名空间和声明
【发布时间】:2015-06-01 17:58:31
【问题描述】:

我在 C# 中创建 xml,并希望添加 Namespace 和 Declaration 。我的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>

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

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

    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

    如果您想简单地“继承”命名空间,那么您将无法以如此流畅的方式执行此操作。您必须使用父元素的命名空间创建 XName,例如:

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

    关于声明,XDocument 在调用 ToString 时不包含此声明。如果您使用Save 写入StreamTextWriter,或者如果您提供的XmlWriter 在其OmitXmlDeclaration = true 中没有OmitXmlDeclaration = true,则会出现这种情况。

    如果您只想获取字符串,this question 有一个使用 StringWriter 的漂亮扩展方法的答案。

    【讨论】:

    • 感谢您的回答。如果我不想在子元素中引用命名空间,那么如何实现?
    • @user1893874 没有简单的方法,我添加了一个可能的选项。如何应用它取决于代码的更广泛上下文。
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回答。我不能只将命名空间添加到 Root 元素吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2023-03-24
    • 2012-12-26
    • 1970-01-01
    • 2010-10-27
    相关资源
    最近更新 更多