XSLT 2.0按条件求和结果不符,求正确实现方案
修正XSLT 2.0条件求和逻辑
核心需求
对每个目标节点执行以下取值规则后求和:
- 若
wd:Analytical_amount > 0,使用该节点的wd:Analytical_amount值 - 若
wd:Analytical_amount = 0,使用该节点的wd:Total_Invoice_amount值
错误原因
原XSLT未针对单个节点执行条件判断后取值,而是直接对两类节点的数值分别求和再合并,导致总和计算偏离预期。
修正后的XSLT实现
使用XSLT 2.0的节点内条件判断结合sum()函数,直接对每个节点的目标取值求和:
<!-- 输出格式:节点数量 | Analytical_amount>0的总和 | 条件求和结果 --> <xsl:template match="/"> <!-- 统计目标节点总数 --> <xsl:value-of select="count(//wd:Invoice)"/>| <!-- 统计Analytical_amount大于0的数值总和(对应输出第二个值) --> <xsl:value-of select="format-number(sum(//wd:Invoice[wd:Analytical_amount > 0]/wd:Analytical_amount), '0.00')"/>| <!-- 核心条件求和:对每个节点按规则取值后求和 --> <xsl:value-of select="sum(//wd:Invoice/(if (wd:Analytical_amount > 0) then wd:Analytical_amount else wd:Total_Invoice_amount))"/>| </xsl:template>
验证示例
原XML场景
假设原XML结构如下:
<wd:Root xmlns:wd="http://example.com"> <wd:Invoice> <wd:Analytical_amount>1500.00</wd:Analytical_amount> <wd:Total_Invoice_amount>5000.00</wd:Total_Invoice_amount> </wd:Invoice> <wd:Invoice> <wd:Analytical_amount>0.00</wd:Analytical_amount> <wd:Total_Invoice_amount>500.00</wd:Total_Invoice_amount> </wd:Invoice> </wd:Root>
修正后输出:2|1500.00|2000.0|,与预期一致。
新增节点场景
新增两个节点后的XML:
<wd:Root xmlns:wd="http://example.com"> <wd:Invoice> <wd:Analytical_amount>1500.00</wd:Analytical_amount> <wd:Total_Invoice_amount>5000.00</wd:Total_Invoice_amount> </wd:Invoice> <wd:Invoice> <wd:Analytical_amount>0.00</wd:Analytical_amount> <wd:Total_Invoice_amount>500.00</wd:Total_Invoice_amount> </wd:Invoice> <wd:Invoice> <wd:Analytical_amount>500.00</wd:Analytical_amount> <wd:Total_Invoice_amount>3000.00</wd:Total_Invoice_amount> </wd:Invoice> <wd:Invoice> <wd:Analytical_amount>0.00</wd:Analytical_amount> <wd:Total_Invoice_amount>0.00</wd:Total_Invoice_amount> </wd:Invoice> </wd:Root>
修正后输出:4|2000.00|2000.0|(可根据实际节点取值调整预期结果)。
内容的提问来源于stack exchange,提问作者Harshit Singh
相关产品推荐
相关产品推荐

