XSLT global replace

I found a code to do a global replace (similar to VBScript Replace function) in XSLT. It's a great example of important XSLT 1.0 concepts: setting variable value with other XSLT tags (function call emulation) and changing a loop into a recursion (as loops are not available in XSLT 1.0). Here is the slightly cleaned-up code. First we define the function (named template) and its parameters:
<xsl:template name="globalReplace">
  <xsl:param name="value"/>
  <xsl:param name="from"/>
  <xsl:param name="to"/>
The xsl:choose is the if-then-else/select replacement. We test if the source substring is present in the value …
  <xsl:choose>
    <xsl:when test="contains($value,$from)">
… if it is, we do tail recursion first, replacing all the remaining values and storing the result in $rest …
      <xsl:param name="rest">
        <xsl:call-template name="globalReplace">
          <xsl:with-param name="outputString" select="substring-after($value,$from)"/>
          <xsl:with-param name="from" select="$from"/>
          <xsl:with-param name="to" select="$to"/>
        </xsl:call-template>
      </xsl:param>
… and then concatenate the substring before the first from value with the to value and the results of the tail recursion.
      <xsl:value-of select="concat(substring-before($value,$from),$to,$rest)" />
    </xsl:when>
If the source string does not contain the substring to be replaced, we just return it (this also ends the tail recursion) …
    <xsl:otherwise>
      <xsl:value-of select="$outputString"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

1 comment:

Naive Bayesian said...

Hi Love the blog.
Keep the XSLT content coming !

Post a Comment