Remove the word 'and' in XSLT using translate function

社会主义新天地 提交于 2019-12-02 05:24:54

问题


I would like to remove the word 'and' from a string using the translate function rather than using a replace .

for instance:

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

in addition to ",:" i would like to remove the word 'and' as well. Please suggest.


回答1:


The translate function can't do this, it can only remove or replace single characters, not multi-character strings. Like so many things in XSLT 1.0 the escape route is a recursive template, the simplest version being:

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

And then call this template when you define the nme variable.

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

Here I'm using translate to remove the single characters and then passing the result to the template to remove "and".

Though as pointed out in the comments, it depends exactly what you mean by "word" - this will remove all occurrences of the string "and" including in the middle of other words, you might want to be more conservative, removing only " and" (space-and), for example.

To remove more than one word you simply call the template repeatedly, passing the result of one call as a parameter to the next

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


来源:https://stackoverflow.com/questions/25784081/remove-the-word-and-in-xslt-using-translate-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!