XSL - 计算金额的总和 [英] XSL - Sum of computed amounts
问题描述
我只需要一些有关 XSL 基本功能的帮助.我想显示先前计算的金额总和.但我不知道该怎么做.有关 XSL 必须与 XSLT 1.0 一起使用的信息,我这边有技术限制.
I just need some help on basic feature of XSL. I would like to display a sum of amounts previously computed. But I do not know how to do it. For information the XSL must work with XSLT 1.0, technical limitation on my side.
例如这是我的 xml.
For instance here is my xml.
<A>
<amount>10</amount>
<rate>4</rate>
</A>
<A>
<amount>-21</amount>
<rate>2</rate>
</A>
<B>
<amount>8</amount>
<rate>1</rate>
</B>
<C>
<amount>7</amount>
<rate>32</rate>
</C>
并且我想显示在 Total 元素中每个金额乘以每个相关比率的总和.
and I would like to display the sum of each amount multiplied by each associated rate within a Total element.
<Total value="230">
<PositiveTotal>
272
</PositiveTotal>
<NegativeTotal>
-42
</NegativeTotal>
</Total>
我不知道该怎么做.
提前致谢
问候,
推荐答案
可能的多种解决方案之一.它会给你一个想法,如何解决这个问题.
One of possible multiple solutions. It will give you an idea, how to solve this.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="root">
<xsl:variable name="positiveTotal">
<xsl:call-template name="sum">
<xsl:with-param name="items" select="*[not(starts-with(amount,'-') or starts-with(rate, '-'))]"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="negativTotal">
<xsl:call-template name="sum">
<xsl:with-param name="items" select="*[starts-with(amount,'-') or starts-with(rate, '-')]"/>
</xsl:call-template>
</xsl:variable>
<Total value="{$positiveTotal + $negativTotal}">
<PositivTotal>
<xsl:value-of select="format-number($positiveTotal, '0')"/>
</PositivTotal>
<NegativeTotal>
<xsl:value-of select="format-number($negativTotal, '0')"/>
</NegativeTotal>
</Total>
</xsl:template>
<xsl:template name="sum">
<xsl:param name="items" />
<xsl:param name="total" select="0" />
<xsl:choose>
<xsl:when test="not($items)">
<xsl:value-of select="$total"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sum">
<xsl:with-param name="items" select="$items[position() > 1]" />
<xsl:with-param name="total"
select="$total + ($items[1]/amount * $items[1]/rate)" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
!! 将 match="root"
更改为您的根节点!给定的 source-xml 无效.
!! Change match="root"
to your root-node! Given source-xml is not valid.
已经有很多sum
问题了!查看屏幕右侧的相关框.
There are already many sum
-questions! See the Related Box on your right side of screen.
这篇关于XSL - 计算金额的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!