Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove xmlns attribute with .NET XML API

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

The resulting output is

xmlns attr before removal=System.Xml.XmlAttribute
xmlns attr after removal=
<Element1 attr1="value1" xmlns="http://mynamespace.com/" />

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.

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: I'm talking about .NET 2.0.

like image 727
axk Avatar asked Sep 16 '08 20:09

axk


1 Answers

Many thanks to Ali Shah, this thread solved my problem perfectly! here's a C# conversion:

var dom = new XmlDocument();
        dom.Load("C:/ExampleFITrade.xml));
        var loaded = new XDocument();
        if (dom.DocumentElement != null)
            if( dom.DocumentElement.NamespaceURI != String.Empty)
            {
                dom.LoadXml(dom.OuterXml.Replace(dom.DocumentElement.NamespaceURI, ""));
                dom.DocumentElement.RemoveAllAttributes();
                loaded = XDocument.Parse(dom.OuterXml);
            }
like image 81
Matt Harris Avatar answered Sep 23 '22 13:09

Matt Harris