我想使用 translate 函数而不是使用 replace 从字符串中删除单词 '和' 。
例如:
<xsl:variable name="nme" select="translate(./Name/text(), ',:, '')" />
Run Code Online (Sandbox Code Playgroud)
除了“,:”,我还想删除“和”这个词。请建议。
该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>
Run Code Online (Sandbox Code Playgroud)
然后在定义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>
Run Code Online (Sandbox Code Playgroud)
在这里,我使用translate删除单个字符,然后将结果传递给模板以删除“和”。
尽管正如评论中所指出的,这完全取决于您所说的“单词”是什么意思——这将删除所有出现的字符串“and”,包括在其他单词的中间,您可能希望更加保守,只删除“和” "(空格和),例如。
要删除多个单词,您只需重复调用模板,将一次调用的结果作为参数传递给下一个
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3477 次 |
| 最近记录: |