3

In XPATH 2.0 there is a function that allows me to replace a substring in a string with another string. I'd like to do this using xalan. Unfortunately, it doesn't support the EXSLT method str:replace and it only uses XSLT 1.0 stylesheets. Including the function from exslt.org doesn't seem to work. If I try using the function style, it complains that it can't find str:replace. If I try using the template style, it complains that it can't find node-set, even though it is supported. translate is useless since it's just a character swap. Any ideas?

Jason Thompson
  • 4,643
  • 5
  • 50
  • 74

1 Answers1

3

You can write your own function which can immitate xslt 2.0 replace :

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

If you call it like this :

<xsl:variable name="replacedString">
<xsl:call-template name="replace">
  <xsl:with-param name="text" select="'This'" />
  <xsl:with-param name="replace" select="'This'" />
  <xsl:with-param name="by" select="'That'" />
</xsl:call-template>

Your resulting $replacedString will have the value "That"

FailedDev
  • 26,680
  • 9
  • 53
  • 73