Friday 8 February 2019

Remove all the namespace from XML using XSLT mapping

There will be an issue in XPATH handling in content modifier/Router/Filter when there is namspace (like ns2:) for all the fields.

To remove all the namespace in the XML payload, use the below XSLT mapping code:

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

(or)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes"/>

    <!-- Stylesheet to remove all namespaces from a document -->
    <!-- NOTE: this will lead to attribute name clash, if an element contains
        two attributes with same local name but different namespace prefix -->
    <!-- Nodes that cannot have a namespace are copied as such -->

    <!-- template to copy elements -->
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>


    <!-- template to copy attributes -->
    <xsl:template match="@*">
        <xsl:attribute name="{local-name()}">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>


    <!-- template to copy the rest of the nodes -->
    <xsl:template match="comment() | text() | processing-instruction()">
        <xsl:copy/>
    </xsl:template>

</xsl:stylesheet>

Input:

<?xml version="1.0" encoding="UTF-8"?>
<ns2:MT_TOnlineBookResponseDetails xmlns:ns2="urn:electrolux.com">
  <BookSuccessfully>true</BookSuccessfully>
  <ErrorCode>0</ErrorCode>
</ns2:MT_TOnlineBookResponseDetails>

Output:

<?xml version="1.0" encoding="UTF-8"?>
<MT_TOnlineBookResponseDetails>
  <BookSuccessfully>true</BookSuccessfully>
  <ErrorCode>0</ErrorCode>
</MT_TOnlineBookResponseDetails>



No comments:

Post a Comment