繁体   English   中英

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

[英]How to sum a value in for-each loop in xslt?

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>

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

我设法通过使用每个循环获取输出:

<xsl:for-each select="/item">
<xsl:value-of select="item_price*gst"/>
</xsl:for-each>

我的假设可能与相似,但似乎不起作用:

谢谢你的帮助 :)

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

XSLT 1.0

对于XSLT 1.0,您需要使用一个递归模板,该模板将跟踪重复的<item>节点的产品累计值( item_price * gst )。

<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>

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>

在两种情况下,您的sum

<sum>2300</sum>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM