【问题标题】:[XSLT]: Remove string in XSLT[XSLT]:删除 XSLT 中的字符串
【发布时间】:2012-11-06 06:26:50
【问题描述】:
我在 xsl 中有字符串“[test]”。我需要删除 xsl 中的这个括号。我怎样才能在 XSL 中实现这一点。请帮忙。
我知道这可以做到,但是我怎样才能用下面的代码删除'[',
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$string" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
请帮忙删除'['和']'
【问题讨论】:
标签:
string
xslt
removeclass
【解决方案1】:
使用translate() 函数。
示例...
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$string" />
<xsl:value-of select="translate( $text, '[]', '')" />
</xsl:call-template>
【解决方案2】:
xsl 2.0
replace('[text]','^[(.*)]$','$1')
xsl 1.0
translate('[text]','[]','')
或
substring-before(substring-after('[text]','['),']')
其中任何一个都可以通过不同的故障模式来满足您的需求。请注意,无论输入是什么,第二个示例都会返回一些内容,但会删除输入中的所有括号。第三个例子只返回一个字符串,如果它有一个初始左括号和一个终端右括号,否则它会返回一个空序列。
【解决方案3】:
如果要将一个符号替换为另一个,可以使用翻译功能(XSLT 1.0、2.0),但如果要替换字符串,可以使用 MSXML 和其他 XSLT 处理器的通用模板:
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="replace"/>
<xsl:param name="with"/>
<xsl:choose>
<xsl:when test="contains($text,$replace)">
<xsl:value-of select="substring-before($text,$replace)"/>
<xsl:value-of select="$with"/>
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="substring-after($text,$replace)"/>
<xsl:with-param name="replace" select="$replace"/>
<xsl:with-param name="with" select="$with"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>