如何使用.NET XML API删除xmlns属性 [英] How to remove xmlns attribute with .NET XML API
问题描述
XmlElement.Attributes.Remove *方法对于任意属性都可以正常工作,从而导致从XmlDocument.OuterXml属性中删除了已删除的属性. Xmlns属性却不同.这是一个示例:
XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:
XmlDocument doc = new XmlDocument();
doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>";
doc.DocumentElement.Attributes.RemoveNamedItem("attr2");
Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]);
doc.DocumentElement.Attributes.RemoveNamedItem("xmlns");
Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]);
结果输出是
xmlns attr before removal=System.Xml.XmlAttribute
xmlns attr after removal=
<Element1 attr1="value1" xmlns="http://mynamespace.com/" />
该属性似乎已从Attributes集合中删除,但并未从XmlDocument.OuterXml中删除. 我猜这是因为该属性的特殊含义.
The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute.
问题是如何使用.NET XML API删除xmlns属性. 显然,我可以从String表示形式中删除该属性,但是我想知道是否可以使用API进行相同的操作.
The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.
@Edit:我正在谈论.NET 2.0.
@ I'm talking about .NET 2.0.
推荐答案
.NET DOM API不支持修改元素的名称空间,这实际上是您要尝试做的事情.因此,为了解决您的问题,您必须以一种或另一种方式构造一个新文档.您可以使用相同的.NET DOM API并创建一个新元素,而无需指定其名称空间.另外,您可以创建XSLT样式表,该样式表将原始的命名空间"文档转换为新的样式,其中的元素将不符合命名空间要求.
.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original "namespaced" document to a new one in which the elements will be not namespace-qualified.
这篇关于如何使用.NET XML API删除xmlns属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!