如何对 xslt 中的 for-each 循环中的值求和?

Vis*_*han 1 xml xslt transformation

XML 文件:

<item>
<item_price>56</item_price>
<gst>10</gst>
</item>
<item>
<item_price>75</item_price>
<gst>10</gst>
</item>
<item>
<item_price>99</item_price>
<gst>10</gst>
</item>
Run Code Online (Sandbox Code Playgroud)

我需要使用 XSLT 对每个 (item_price*gst) 求和

我已经设法通过使用每个循环来获得单独的输出:

<xsl:for-each select="/item">
<xsl:value-of select="item_price*gst"/>
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

我的假设可能是这样的,但它似乎不起作用:

感谢您的帮助 :)

小智 5

根据您使用的 XSLT 处理器,XSLT 1.0 和 XSLT 2.0 的解决方案有所不同。

XSLT 1.0

对于 XSLT 1.0,您需要使用递归模板来跟踪重复节点的乘积 ( item_price* ) 的累积值。gst<item>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <xsl:template match="items">
        <sum>
            <xsl:call-template name="sumItems">
                <xsl:with-param name="nodeSet" select="item" />
            </xsl:call-template>
        </sum>
    </xsl:template>

    <xsl:template name="sumItems">
        <xsl:param name="nodeSet" />
        <xsl:param name="tempSum" select="0" />

        <xsl:choose>
            <xsl:when test="not($nodeSet)">
                <xsl:value-of select="$tempSum" />
            </xsl:when>
            <xsl:otherwise>
                <xsl:variable name="product" select="$nodeSet[1]/item_price * $nodeSet[1]/gst" />
                <xsl:call-template name="sumItems">
                    <xsl:with-param name="nodeSet" select="$nodeSet[position() > 1]" />
                    <xsl:with-param name="tempSum" select="$tempSum + $product" />
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

XSLT 2.0

对于 XSLT 2.0,可以使用sum(item/(item_price * gst))表达式来计算乘积之和。

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="items">
        <sum>
            <xsl:value-of select="sum(item/(item_price * gst))" />
        </sum>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,您都会得到sumas

<sum>2300</sum>
Run Code Online (Sandbox Code Playgroud)