关于xalan:如何在XSLT / XPATH 1.0中执行str:replace?

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

在XPATH 2.0中,有一个函数允许我用另一个字符串替换一个字符串中的子字符串。我想使用xalan做到这一点。不幸的是,它不支持EXSLT方法str:replace,它仅使用XSLT 1.0样式表。包括来自exslt.org的功能似乎无效。如果我尝试使用函数样式,它将抱怨找不到str:replace。如果我尝试使用模板样式,它会抱怨即使支持它也找不到节点集。翻译是没有用的,因为它只是字符交换。有什么想法吗?


您可以编写自己的函数来模仿xslt 2.0替换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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>

如果您这样称呼它:

1
2
3
4
5
6
<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>

您得到的$ replacedString的值为" That"