首页 > 解决方案 > 从 xml 中删除 xmlns 属性

问题描述

在下面的 xml 中,我尝试删除 xmlns 属性,但是它无法填充,xmlNode.Attributes 仍然出现在 externalxml 和最终的 xmldocument 下。

... 
<z:Datac knid="2" xmlns="http://services/api/"></z:Datac>
...
<z:Datac knid="3" xmlns="http://services/api/"></z:Datac>
....
<z:Datac knid="5" xmlns="http://services/api/"></z:Datac>
....

如何删除每个 z:Datac 元素的 xmlns 属性。

foreach (var item in nodes)
                    {
                        var xmlnsAttribute = (item.Attributes has "xmlns" attribute)
                        if (xmlnsAttribute != null)
                        {
                            Remove xmlNode...  //not able to reach here as not able to find xmlns.
                        }
}

没有 xml.linq

标签: c#xmlc#-4.0xmldocumentxmlnode

解决方案


你会想要类似的东西:

XmlDocument doc = new XmlDocument();
doc.Load("my.xml");
foreach(var node in doc.DocumentElement.ChildNodes)
{
    var el = node as XmlElement;
    if (el != null)
    {
        if (el.HasAttribute("xmlns"))
        {
            var ns = el.GetAttribute("xmlns");
            if (ns != null && ns != el.NamespaceURI)
            {
                el.RemoveAttribute("xmlns");
            }
        }
    }
}
doc.Save("new.xml");

显然,您可能希望在复杂场景中对其进行查询或发出全元素查询。


推荐阅读