web analytics

XSLT Template: Implementing a String Replace Function With Recursion

Options

codeling 1602 - 6666
@2021-03-03 08:01:20

The following XSLT template demostates how to implement a string replace function with recursion.

<xsl:template name="replace-with">
  <xsl:param name="theString"/>
  <xsl:param name="what"/>
  <xsl:param name="with"/>
  <xsl:choose>
    <xsl:when test="contains($theString,$what)">
      <xsl:variable name="after" select="substring-after($theString, $what)"/>
      <xsl:variable name="before" select="substring-before($theString, $what)"/>
      <xsl:variable name="newValue" select="concat($before, $with, $after)" />
      <xsl:choose>
        <xsl:when test="contains($newValue, $what)">
          <xsl:call-template name="replace-with">
            <xsl:with-param name="theString" select="$newValue" />
            <xsl:with-param name="what" select="$what" />
            <xsl:with-param name="with" select="$with" />
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$newValue"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$theString"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

The following code snippet shows you how to use the above template:

....
< xsl:variable name="abc">
< xsl:call-template name="replace-with">
< xsl:with-param name="theString" select="text()" />
  <xsl:with-param name="what" select="'Hella'" />
  <xsl:with-param name="with" select="'Hello'" />
< /xsl:call-template>
< /xsl:variable>
< xsl:value-of select="$abc" />
....

 

@2021-03-03 22:24:52

If you just want a XSLT template that replaces the first occurrence of the replacement substring, you can implement it like the following code:

 <xsl:template name="first-occurence-replace-with">
  <xsl:param name="theString"/>
  <xsl:param name="what"/>
  <xsl:param name="with"/>
  <xsl:choose>
   <xsl:when test="contains($theString,$what)">
    <xsl:variable name="after" select="substring-after($theString, $what)"/>
    <xsl:variable name="before" select="substring-before($theString, $what)"/>
    <xsl:value-of select="concat(concat($before, $with), $after)"/>
   </xsl:when>
   <xsl:otherwise>
    <!-- In case $what isn't found in $theString -->
    <xsl:value-of select="$theString"/>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com