Search code examples
xsltxslt-1.0xslt-2.0

Remove namespace from the xml


Below is the Input XML that I am trying to convert to another xml without namespace. I tried to remove namespace but it is not working. All the required details are provided below for the request.

 <ns1:FieldResponse
    xmlns:ns1="http://www.example.org">
    <ns1:response>
        <ns1:Elements>
            <ns1:workRequestId>12123</ns1:workRequestId>
        </ns1:Elements>
    </ns1:response>
    <ns1:Status>1232</ns1:Status>
   </ns1:FieldResponse>

Expected Output:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <Elements>
        <workRequestId>12123</workRequestId>
    </Elements>
</response>
<Status>1232</Status>

Output after the XSLT

<?xml version="1.0" encoding="UTF-8"?>
<response
    xmlns:ns1="http://www.example.org">
    <cmElements>
        <workRequestId>12123</workRequestId>
    </cmElements>
</response>
<Status
    xmlns:ns1="http://www.example.org">1232
</Status>

XSLT Used :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"   xmlns:ns1="http://www.example.org"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<response>
<Elements>
<workRequestId>
<xsl:value-of   select="/ns1:FieldResponse/ns1:response/ns1:Elements/ns1:workRequestId"/>
</workRequestId>
</Elements>
 
<xsl:for-each select="/ns1:FieldResponse/ns1:response/ns1:fault">
<fault>
<xsl:for-each select="./*">
<xsl:element name="{local-name()}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</fault>
</xsl:for-each>
 
</response>
 
<Status>
<xsl:value-of   select="/ns1:FieldResponse/ns1:Status"/>
</Status>
 
</xsl:template>
</xsl:stylesheet>

Solution

  • You could do:

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

    Do note that the output is an XML fragment (no single root element), not a well-formed XML document.