xmlxslt

XSLT template condition based on xml tag to update XML string tag


I have a unique issue with XSLT 1.0. Below is my input XML.

XML:

<request>        
    <xml>
        <![CDATA[<format>1</format><account>5024734061</account><amount>$118.23</amount><dueDate>07/15/2024</dueDate>]]>
    </xml>
    <credit>Y</credit>
    <debit>N</debit>
</request>

And Output XML :

Based on the value of credit or debit tag as Y, It should show amount as Credit: $118.23 or Debit: $118.23 as tag.

if the credit tag has value Y , then the XML string tag should have tag as credit and followed by amount as shown below:

<xml>
    <![CDATA[<format>1</format><account>5024734061</account><credit>$118.23</credit><dueDate>07/15/2024</dueDate>]]>
</xml> 

Solution

  • To do this in pure XSLT 1.0 you would have to do something like:

    <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" cdata-section-elements="xml"/>
    
    <xsl:template match="/request">
        <xml>   
            <xsl:call-template name="replace">
                <xsl:with-param name="string" select="normalize-space(xml)"/>
                <xsl:with-param name="search-string" select="'amount'"/>
                <xsl:with-param name="replace-string" select="name((credit|debit)[.='Y'])"/>
            </xsl:call-template>
        </xml>
    </xsl:template>
    
    <xsl:template name="replace">
        <xsl:param name="string"/>
        <xsl:param name="search-string"/>
        <xsl:param name="replace-string"/>
        <xsl:choose>
            <xsl:when test="contains($string, $search-string)">
                <xsl:value-of select="substring-before($string, $search-string)"/>
                <xsl:value-of select="$replace-string"/>
                <xsl:call-template name="replace">
                    <xsl:with-param name="string" select="substring-after($string, $search-string)"/>
                    <xsl:with-param name="search-string" select="$search-string"/>
                    <xsl:with-param name="replace-string" select="$replace-string"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$string"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    
    </xsl:stylesheet>
    

    This is of course assuming that the original xml payload does not contain the search-string "amount" anywhere else other than in the amount "element" name.