3

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

4

1 回答 1

3

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

<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>

如果你这样称呼它:

<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 将具有值“那个”

于 2011-10-06T16:20:22.727 回答