Saturday, January 10, 2015

Adding namespace and prefix to only root tag using XSLT

1. Lets assume that we have following XML content.

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
    <ByExchangeRateQuery>  
    <MessageHeader>  
        <CreationDateTime></CreationDateTime>  
    </MessageHeader>  
    <ExchangeRate>  
        <rateCode>M</rateCode>  
        <CurrencyUnit>*</CurrencyUnit>  
        <Currency>*</Currency>  
        <DateTime>2014-06-10T02:27:36Z</DateTime>  
    </ExchangeRate>  
</ByExchangeRateQuery>
   </soapenv:Body>
</soapenv:Envelope>
2. Add the namespace and prefix only for the root tag.
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
   <soapenv:Body>
      <ns0:ByExchangeRateQuery xmlns:ns0="http://test.com/test/wso2/blog/Sample">
         <MessageHeader>
            <CreationDateTime/>
         </MessageHeader>
         <ExchangeRate>
            <rateCode>M</rateCode>
            <CurrencyUnit>*</CurrencyUnit>
            <Currency>*</Currency>
            <DateTime>2014-06-10T02:27:36Z</DateTime>
         </ExchangeRate>
      </ns0:ByExchangeRateQuery>
   </soapenv:Body>
</soapenv:Envelope>

3. Define the XSLT file.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>
    <!--match all the nodes and attributes-->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*">
        </xsl:apply-templates></xsl:copy>
    </xsl:template>
    <!--Select the element need to be apply the namespace and prefix -->
    <xsl:template match="ByExchangeRateQuery">
        <!--Define the namespace with prefix ns0 -->
        <xsl:element name="ns0:{name()}" namespace="http://test.com/test/wso2/blog/Sample">
            <!--apply to above selected node-->
            <xsl:apply-templates select="node()|@*">
        </xsl:apply-templates></xsl:element>
    </xsl:template>
</xsl:stylesheet>