xslt-1.0soa

How to remove default namespace xmlns using XSLT?


I have a XML file having default namespace xmlns="http://www.xxxx.com/xyz" and target namespace xmlns:tns="http://www.xxxx.com/xyz" , Both need to be removed

<?xml version="1.0" encoding="UTF-8" ?>
<Root xmlns:tns="http://www.xxxx.com/xyz" xmlns="http://www.xxxx.com/xyz">
    <Header type="XXXX" purpose="Original" xmlns="">
        <ID>XXXXXX</ID>
    </Header>
</Root>

I use the below code but it doesn't remove the default namespace xmlns="http://www.xxxx.com/xyz" from the root element

   <xsl:template match="*">
    <!-- remove element prefix -->
    <xsl:element name="{local-name()}">
      <!-- process attributes -->
      <xsl:for-each select="@*">
        <!-- remove attribute prefix -->
        <xsl:attribute name="{local-name()}">
          <xsl:value-of select="."/>
        </xsl:attribute>
      </xsl:for-each>
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>

Can anyone help to suggest how to solve this case?

XML image for your reference

xmlns Namespace issue


Solution

  • If you want to remove the default namespace then you cannot put the renamed elements back into their original namespace.

    Seeing that the attributes in your example are not in a namespace (as is most often the case), I believe you could do simply:

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Demo here.