2015-07-13 82 views
0

我有一个XmlWriter,它已经有一个xmlns属性集的根元素。用XmlWriter命名空间编写XElement?

我现在有一个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> 

回答

0

是什么让你认为这是无效的? The spec说:

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

如果你想删除它,那么你需要写它之前,你XElement及其后代的命名空间设置为相同的命名空间和您现有的根元素。你可以做到这一点,在创建时:

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

好吧,其实我在另一篇文章阅读,它可能是空的,但是这仅仅是默认行为:

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

或者事后,而不是我们之后可以设置的东西。也许我误解了 – J4N