如何使用 .NET XML API 删除 xmlns 属性 [英] How to remove xmlns attribute with .NET XML API

查看:29
本文介绍了如何使用 .NET XML API 删除 xmlns 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 属性.显然我可以从它的字符串表示中删除属性,但我想知道是否可以使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆