简体   繁体   中英

Remove xmlns attribute from xml

In below xml, I tried to delete xmlns attribute but, its unable to populate under, xmlNode.Attributes still appear under outerxml and final 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>
....

How to remove xmlns attribute for each z:Datac element.

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.
                        }
}

don't have xml.linq

I guess you'd want something like:

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");

Obviously you'd probably want to make it query, or issue an all-elements query, in complex scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM