Search code examples
xslt-1.0xslt-2.0

Remove Namespace on Element


I want to remove namespace at output structure. I prepared XSLT code but it gives namespace on this element

My Input XML is this.

<?xml version='1.0' encoding='UTF-8'?> 
<n0:Messages xmlns:n0="http://sap.com/xi/XI"> 
<n0:Message> 
        <ContactData>   
        <Data>
          <information>
                  <Name>A</Name>
                  <Phone>123456</Phone>   
          </information>
        </Data> 
        </ContactData> 
</n0:Message>
</n0:Messages>

XSLT CODE implemented

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:n0="http://sap.com/xi/XI" exclude-result-prefixes="n0">

<!-- Output -->
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
     <xsl:copy-of select= "//ContactData"/>
</xsl:template>
<xsl:template match="//*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>

Present output:

<?xml version='1.0' encoding='UTF-8'?>  
        <ContactData xmlns:n0="http://sap.com/xi/XI">   
        <Data>
          <information>
                  <Name>A</Name>
                  <Phone>123456</Phone>   
          </information>
        </Data> 
        </ContactData> 

Output expected

<?xml version='1.0' encoding='UTF-8'?>  
            <ContactData>   
            <Data>
              <information>
                      <Name>A</Name>
                      <Phone>123456</Phone>   
              </information>
            </Data> 
            </ContactData> 

Please help on this code Thank you very much.


Solution

  • If you're able to use XSLT 2.0, you can achieve the required output simply by:

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/">
        <xsl:copy-of select="*/*/*" copy-namespaces="no"/>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Demo: https://xsltfiddle.liberty-development.net/3NSSEuK


    In XSLT 1.0, it takes a bit more work:

    <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:strip-space elements="*"/>
    
    <xsl:template match="/">
        <xsl:apply-templates select="*/*/*" />
    </xsl:template>
    
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Demo: https://xsltfiddle.liberty-development.net/3NSSEuK/1