使用count为字符串添加s的XSLT实现,求更优方案
更优的XSLT单复数输出实现方式
你的现有实现虽然能完成需求,但存在大量重复代码,后续修改文本时需要改动两处,维护成本较高。以下是不同XSLT版本下的更优实现:
XSLT 2.0 及更高版本
可以直接在固定文本中插入条件判断的后缀,避免重复编写整段内容:
<li>Changes to the <i>Reference</i> section have been made to the following template<xsl:if test=".//Count != 1">s</xsl:if>:</li>
这种方式只针对变化的后缀部分做判断,代码更简洁,后续修改主体文本只需操作一次。
如果偏好使用字符串拼接的方式,也可以这样写(注意需要开启disable-output-escaping来保留<i>标签的格式):
<li> <xsl:value-of select="concat('Changes to the <i>Reference</i> section have been made to the following template', if (.//Count != 1) then 's' else '', ':')" disable-output-escaping="yes"/> </li>
XSLT 1.0
由于XSLT 1.0不支持原生的if表达式,我们可以把重复的文本抽出来,只针对变化的单词做判断:
<li>Changes to the <i>Reference</i> section have been made to the following <xsl:choose> <xsl:when test=".//Count = 1">template</xsl:when> <xsl:otherwise>templates</xsl:otherwise> </xsl:choose>: </li>
相比你的原代码,这种写法大幅减少了重复内容,维护性更好。
另外也可以用字符串拼接结合布尔值转数字的技巧实现:
<li> <xsl:value-of select="concat('Changes to the <i>Reference</i> section have been made to the following template', substring('s', 1, number(.//Count != 1)), ':')" disable-output-escaping="yes"/> </li>
这里number(.//Count != 1)会在条件成立时返回1,否则返回0,substring('s', 1, 1)会取出"s",而substring('s', 1, 0)则返回空字符串,以此实现后缀的动态添加。
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

