How can I remove the "xmlns:..." namespace information from each XML element in C#?
Be careful about what you are asking for. The namespace information in larger or more complex XML files is an integral part of the document map. Removing all namespaces may make navigation through the tree more problematic.
Zombiesheep's cautionary answer notwithstanding, my solution is to wash the xml with an xslt transform to do this.
wash.xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Can't you just read the file, find and remove all xmlns="..."? Why should it be hard?
I had a similar problem (needing to remove a namespace attribute from a particular element, then return the XML as an XmlDocument
to BizTalk) but a bizarre solution.
Before loading the XML string into the XmlDocument
object, I did a text replacement to remove the offending namespace attribute. It seemed wrong at first as I ended up with XML that could not be parsed by the "XML Visualizer" in Visual Studio. This is what initially put me off this approach.
However, the text could still be loaded into the XmlDocument
and I could output it to BizTalk fine.
Note too that earlier, I hit one blind alley when trying to use childNode.Attributes.RemoveAll()
to remove the namespace attribute - it just came back again!