10

How can I remove the "xmlns:..." namespace information from each XML element in C#?

Marc
  • 9,012
  • 13
  • 57
  • 72

3 Answers3

10

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>
annakata
  • 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
  • Great post annakata :] Thank you! – cc0 Mar 07 '11 at 07:06
7

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));
    }
}
Simon
  • 33,714
  • 21
  • 133
  • 202
2

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!

NickBeaugié
  • 720
  • 9
  • 17