【问题标题】:Write XElement with XmlWriter with the XmlWriter namespace?使用 XmlWriter 命名空间编写 XElement?
【发布时间】:2015-07-13 12:19:28
【问题描述】:

我有一个 XmlWriter,它已经有一个带有 xmlns 属性集的根元素。

我现在有一个 XElement(有很多子元素),没有指定命名空间。

如果我这样做:

    xElement.WriteTo(writer);

我以无效的 xml 结尾:

<MyRootElement xmlns="SomeNameSpace">
    <!-- Some elements of this namespace -->

    <MyXElementType  xmlns="">
        <!-- A lot of other Element in the same namespace -->
    </MyXelementType>
    <!-- Some elements of this namespace -->
</MyRootElement>

因为禁止指定空的命名空间。这是有问题的,因为我需要在 XSD 之后进行验证。

我能做些什么来结束这个:

    <MyXElementType><!-- HERE, no xmlns !!! -->
        <!-- A lot of other Element in the same namespace -->
    </MyXelementType>
    <!-- Some elements of this namespace -->
</MyRootElement>

【问题讨论】:

    标签: c# .net xml xelement xmlwriter


    【解决方案1】:

    是什么让您认为它无效? The spec 说:

    默认命名空间声明中的属性值可以为空。在声明的范围内,这与没有默认命名空间的效果相同。

    如果要删除它,则需要在编写之前将 XElement 及其后代的命名空间设置为与现有根元素相同的命名空间。您可以在创建时执行此操作:

    XNamespace ns = "SomeNamespace";
    var element = new XElement(ns + "MyXElementType");
    

    或者事后:

    foreach (var element in element.DescendantsAndSelf())
    {
        element.Name = ns + element.Name.LocalName;
    }
    

    【讨论】:

    • 好吧,事实上我在另一篇文章中读到,它可能是空的,但这只是默认行为,不是我们以后可以设置的。可能我理解错了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2010-11-03
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多