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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With