如何使用XSLT 1.0对字符串中的数值求和?
在XSLT 1.0中对空格分隔的带单位数值求和
原代码的问题
- XSLT 1.0不支持
replace()函数,这是XSLT 2.0及以上版本的特性,直接使用会导致报错。 - 原模板输出的是字符串形式的加法表达式,而非实际计算出的数值总和,无法直接作为数值变量使用。
修正后的递归实现(XSLT 1.0兼容)
这是XSLT 1.0中处理此类需求的标准简便方案,通过递归遍历并累加数值:
<!-- 核心求和模板 --> <xsl:template name="sum-space-separated-values"> <xsl:param name="input" /> <xsl:param name="total" select="0" /> <!-- 去除首尾空格,处理连续空格的情况 --> <xsl:variable name="trimmed-input" select="normalize-space($input)" /> <xsl:choose> <xsl:when test="$trimmed-input != ''"> <!-- 提取第一个分隔项 --> <xsl:variable name="first-item" select="substring-before(concat($trimmed-input, ' '), ' ')" /> <!-- 提取项中的纯数字:移除所有非数字、非小数点的字符 --> <xsl:variable name="first-number" select="translate($first-item, translate($first-item, '0123456789.', ''), '')" /> <!-- 剩余待处理的内容 --> <xsl:variable name="remaining-items" select="substring-after($trimmed-input, ' ')" /> <!-- 递归调用,累加当前数值到总和 --> <xsl:call-template name="sum-space-separated-values"> <xsl:with-param name="input" select="$remaining-items" /> <xsl:with-param name="total" select="$total + number($first-number)" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <!-- 所有项处理完成,返回最终总和 --> <xsl:value-of select="$total" /> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- 使用示例 --> <xsl:variable name="cols" select="'10 20 30 20pt'" /> <xsl:variable name="total_width"> <xsl:call-template name="sum-space-separated-values"> <xsl:with-param name="input" select="$cols" /> </xsl:call-template> </xsl:variable> <!-- 若需要保留单位(如统一添加pt) --> <xsl:variable name="total_width_with_unit" select="concat($total_width, 'pt')" />
逻辑说明
normalize-space:处理输入字符串中的首尾空格和连续空格,确保分割逻辑稳定。translate嵌套用法:先提取所有非数字/小数点的字符,再将这些字符从项中移除,得到纯数字字符串。- 递归累加:通过
total参数传递当前累加结果,最终返回总和,避免了原代码中输出表达式的错误。
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

