C# 使用XmlWriter和XmlWriter命名空间编写XElement?
我有一个XmlWriter,它已经有了一个根元素和C# 使用XmlWriter和XmlWriter命名空间编写XElement?,c#,.net,xml,xelement,xmlwriter,C#,.net,Xml,Xelement,Xmlwriter,我有一个XmlWriter,它已经有了一个根元素和xmlns属性集 <MyXElementType><!-- HERE, no xmlns !!! --> <!-- A lot of other Element in the same namespace --> </MyXelementType> <!-- Some elements of this namespace --> </MyRo
xmlns
属性集
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
我现在有一个XElement(有很多子元素),没有指定名称空间
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
如果我这样做:
xElement.WriteTo(writer);
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
我以无效的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>
<MyXElementType><!-- HERE, no 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>
我能做些什么来结束这一切:
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
是什么让你认为它是无效的?说:
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
默认命名空间声明中的属性值可能为空。在声明的范围内,这与没有默认名称空间具有相同的效果
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
如果要删除它,则需要在写入之前将XElement
及其子元素的命名空间设置为与现有根元素相同的命名空间。您可以在创建时执行以下操作:
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
XNamespace ns = "SomeNamespace";
var element = new XElement(ns + "MyXElementType");
或事后:
<MyXElementType><!-- HERE, no xmlns !!! -->
<!-- A lot of other Element in the same namespace -->
</MyXelementType>
<!-- Some elements of this namespace -->
</MyRootElement>
foreach (var element in element.DescendantsAndSelf())
{
element.Name = ns + element.Name.LocalName;
}
好的,事实上我在另一篇文章中读到,它可以是空的,但这只是默认的行为,而不是我们以后可以设置的。也许我误解了