You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XSLT 1.0使用sum计算带双引号的Amount字段返回NaN如何解决

XSLT 1.0 带双引号Amount字段求和解决方案

问题原因

XSLT 1.0 的 sum() 函数仅支持直接对节点集的数值内容求和,不支持在参数内直接对节点文本做字符串转换后再累加。你之前的写法将translate()直接放在节点路径中,无法对每个Amount节点的内容逐一处理后再传入sum(),因此会失效。

原生兼容解决方案(无需扩展,全处理器支持)

使用递归模板实现逐个处理Amount节点、移除双引号后累加的逻辑:

  1. 首先定义递归求和模板:
<xsl:template name="sumAmountWithoutQuotes">
  <xsl:param name="amountNodes" select="/.." />
  <xsl:param name="currentTotal" select="0" />
  <xsl:choose>
    <xsl:when test="$amountNodes">
      <!-- 移除当前节点的双引号后转成数值 -->
      <xsl:variable name="cleanVal" select="number(translate($amountNodes[1]/text(), '&quot;', ''))" />
      <xsl:call-template name="sumAmountWithoutQuotes">
        <xsl:with-param name="amountNodes" select="$amountNodes[position() > 1]" />
        <!-- 仅当数值有效时累加,否则跳过 -->
        <xsl:with-param name="currentTotal" select="$currentTotal + (boolean($cleanVal = $cleanVal) * $cleanVal)" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$currentTotal" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>
  1. 调用模板时先筛选符合条件的Amount节点传入:
<!-- 先筛选符合条件的Amount节点 -->
<xsl:variable name="targetNodes" select="//section1[(field1 = $field1) and (field2 = $field2) and (field3 = $field3)]/Amount" />
<!-- 调用递归模板求和 -->
<xsl:call-template name="sumAmountWithoutQuotes">
  <xsl:with-param name="amountNodes" select="$targetNodes" />
</xsl:call-template>

按你提供的示例输入,当$field1=1、$field2=2、$field3=3时,返回结果为25.15,符合预期。

可选扩展方案(需处理器支持EXSLT)

如果你的XSLT处理器支持EXSLT扩展,可以用更简洁的写法,需要先在样式根节点声明扩展命名空间:

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:str="http://exslt.org/strings"
  xmlns:math="http://exslt.org/math"
  extension-element-prefixes="str math">

<!-- 直接调用EXSLT函数求和 -->
<xsl:value-of select="math:sum(//section1[(field1 = $field1) and (field2 = $field2) and (field3 = $field3)]/Amount/number(translate(., '&quot;', '')))" />

内容的提问来源于stack exchange,提问作者Ivan Yurchenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:48:03