如何在XSLT中统计多个匹配元素的字符总数?
统计多个type为main的abstract元素字符总数的解决方案
原代码的问题在于:当存在多个abstract[@type='main']节点时,normalize-space()仅会处理节点集中的第一个节点,导致统计结果只包含单个节点的内容长度,无法累加所有匹配节点的字符数。
针对XSLT 2.0及以上版本
利用XSLT 2.0支持的节点序列和聚合函数,可以直接通过sum()对每个匹配节点的长度求和:
<xsl:variable name="mainAbstractTotal"> <xsl:value-of select="sum(abstract[@type = 'main']/string-length(normalize-space(.)))" /> </xsl:variable>
这段代码的逻辑是:
- 选中所有
type='main'的abstract节点; - 对每个节点执行
string-length(normalize-space(.)),得到该节点去除首尾空格并合并内部空格后的字符长度; - 用
sum()函数累加所有节点的长度值,得到总字符数。
针对XSLT 1.0版本
XSLT 1.0不支持直接对节点集的计算结果求和,需要通过递归模板遍历节点并累加:
<!-- 定义变量调用递归模板 --> <xsl:variable name="mainAbstractTotal"> <xsl:call-template name="sumAbstractLengths"> <xsl:with-param name="nodes" select="abstract[@type = 'main']" /> </xsl:call-template> </xsl:variable> <!-- 递归求和模板 --> <xsl:template name="sumAbstractLengths"> <xsl:param name="nodes" /> <xsl:param name="total" select="0" /> <xsl:choose> <xsl:when test="$nodes"> <!-- 递归处理剩余节点,累加当前节点的长度 --> <xsl:call-template name="sumAbstractLengths"> <xsl:with-param name="nodes" select="$nodes[position() > 1]" /> <xsl:with-param name="total" select="$total + string-length(normalize-space($nodes[1]))" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <!-- 所有节点处理完毕,返回总长度 --> <xsl:value-of select="$total" /> </xsl:otherwise> </xsl:choose> </xsl:template>
可选调整
如果不需要去除内容中的空格(包括首尾和内部连续空格),可以直接去掉normalize-space(),改用string-length(.)计算原始内容的字符长度。
内容的提问来源于stack exchange,提问作者Hamza Ibraheem
相关产品推荐
相关产品推荐

