删除'和'在XSLT中使用translate函数

时间:2014-09-11 09:40:49

标签: xml xslt xslt-1.0

我想使用translate函数从字符串中删除“”一词,而不是使用替换。

例如:

 <xsl:variable name="nme" select="translate(./Name/text(), ',:, '')" />

除了“,”之外我还想删除“”这个词。请建议。

1 个答案:

答案 0 :(得分:4)

translate函数无法执行此操作,它只能删除或替换单个字符,而不能删除或替换多字符字符串。像XSLT 1.0中的许多东西一样,转义路由是一个递归模板,最简单的版本是:

<xsl:template name="removeWord">
  <xsl:param name="word" />
  <xsl:param name="text" />

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

然后在定义nme变量时调用此模板。

<xsl:variable name="nme">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="'and'" /><!-- note quotes-in-quotes -->
    <xsl:with-param name="text" select="translate(Name, ',:', '')" />
  </xsl:call-template>
</xsl:variable>

我在这里使用translate删除单个字符,然后将结果传递给模板以删除&#34;和&#34;。

虽然正如评论中指出的那样,它完全取决于你的意思&#34; word&#34; - 这将删除所有出现的字符串&#34;和&#34;包括在其他词中间,你可能想要更保守,只删除&#34;和&#34; (例如,空间和)。

要删除多个单词,只需重复调用模板,将一个调用的结果作为参数传递给下一个

<xsl:variable name="noEdition">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="'Edition'" />
    <xsl:with-param name="text" select="translate(Name, ',:', '')" />
  </xsl:call-template>
</xsl:variable>

<xsl:variable name="nme">
  <xsl:call-template name="removeWord">
    <xsl:with-param name="word" select="' and'" />
    <xsl:with-param name="text" select="$noEdition" />
  </xsl:call-template>
</xsl:variable>
相关问题