How can I remove the "xmlns:..." namespace information from each XML element in C#?
-
Are you looking to take a file, replace the text and re-save? – Ray Booysen Jan 05 '09 at 13:17
-
No I receive the XML in string format and have to transform it to HTML (still in string format). – Marc Jan 05 '09 at 14:33
3 Answers
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>

- 74,572
- 17
- 113
- 180
-
Thank you very much for this. That's exactly what I was looking for: Now I first transform the XML with this XSL, then I apply my XSL on the output. You saved my day! – Marc Jan 05 '09 at 15:22
-
From here http://simoncropp.com/working-around-xml-namespaces
var xDocument = XDocument.Parse(
@"<root>
<f:table xmlns:f=""http://www.w3schools.com/furniture"">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>");
xDocument.StripNamespace();
var tables = xDocument.Descendants("table");
public static class XmlExtensions
{
public static void StripNamespace(this XDocument document)
{
if (document.Root == null)
{
return;
}
foreach (var element in document.Root.DescendantsAndSelf())
{
element.Name = element.Name.LocalName;
element.ReplaceAttributes(GetAttributes(element));
}
}
static IEnumerable GetAttributes(XElement xElement)
{
return xElement.Attributes()
.Where(x => !x.IsNamespaceDeclaration)
.Select(x => new XAttribute(x.Name.LocalName, x.Value));
}
}

- 33,714
- 21
- 133
- 202
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!

- 720
- 9
- 17