XmlElement.Attributes.Remove* 方法适用于任意属性,可以将被删除的属性从 XmlDocument.OuterXml 属性中移除。但是 Xmlns 属性不同。以下是一个示例:
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/" />
这个属性似乎已经从属性集合中移除了,但它没有从XmlDocument.OuterXml中删除。 我猜这是因为这个属性的特殊含义所致。
问题在于如何使用.NET XML API删除xmlns属性。 显然,我可以从字符串表示中直接删除该属性,但我想知道是否可以使用API做到同样的事情。
@编辑:我在谈论.NET 2.0。