如何在XSLT中将特殊字符替换为单词/字符串?
解决XSLT中把
/替换为单词and的问题 嘿,我注意到你想把Category元素的CleanName属性里的单个/替换成单词and,但你当前用translate()的方式没法实现这个需求——因为translate()是单字符替换工具,它只能把一个字符换成另一个字符,没法直接替换成多字符的单词。比如你写的translate('Cd /dvd inlays', '/ ', 'and'),实际效果是把/换成a,空格换成n,最后那个d根本派不上用场,完全不是你想要的结果。
下面给你两种可行的解决方案,根据你使用的XSLT版本来选:
方案1:XSLT 2.0及以上(推荐,更简洁)
用replace()函数就能直接实现多字符替换,代码如下:
<xsl:output omit-xml-declaration="yes" indent="yes"/> <!-- 身份模板:默认复制所有节点和属性 --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- 专门处理Category的CleanName属性 --> <xsl:template match="*[local-name()='Category']/@CleanName"> <xsl:attribute name="CleanName"> <!-- 把所有/替换成and --> <xsl:value-of select="replace(., '/', 'and')"/> </xsl:attribute> </xsl:template>
方案2:XSLT 1.0(无replace()函数时用)
XSLT 1.0没有内置的多字符替换函数,我们可以用递归模板来实现:
<xsl:output omit-xml-declaration="yes" indent="yes"/> <!-- 身份模板:默认复制所有节点和属性 --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- 匹配目标属性,调用递归替换模板 --> <xsl:template match="*[local-name()='Category']/@CleanName"> <xsl:attribute name="CleanName"> <xsl:call-template name="replace-slash-with-and"> <xsl:with-param name="input-text" select="."/> </xsl:call-template> </xsl:attribute> </xsl:template> <!-- 递归模板:逐个替换/为and --> <xsl:template name="replace-slash-with-and"> <xsl:param name="input-text"/> <xsl:choose> <xsl:when test="contains($input-text, '/')"> <!-- 截取第一个/之前的内容,添加and,再处理剩下的文本 --> <xsl:value-of select="substring-before($input-text, '/')"/> <xsl:text>and</xsl:text> <xsl:call-template name="replace-slash-with-and"> <xsl:with-param name="input-text" select="substring-after($input-text, '/')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <!-- 没有/了,直接输出剩余文本 --> <xsl:value-of select="$input-text"/> </xsl:otherwise> </xsl:choose> </xsl:template>
这两种方案都能帮你把CleanName里的/替换成and,比如Cd /dvd inlays会变成Cd and dvd inlays。
内容的提问来源于stack exchange,提问作者jeroen poortman
相关产品推荐
相关产品推荐

