开发者

How do I do a str:replace in XSLT/XPATH 1.0?

开发者 https://www.devze.com 2023-04-11 00:33 出处:网络
In XPATH 2.0 there is a funct开发者_开发百科ion 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 meth

In XPATH 2.0 there is a funct开发者_开发百科ion 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?


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"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号