首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在xslt中的for-每个循环中求和值?

如何在xslt中的for-每个循环中求和值?
EN

Stack Overflow用户
提问于 2018-08-13 07:11:19
回答 1查看 7.1K关注 0票数 1

XML文件:

代码语言:javascript
复制
<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)进行求和。

通过为每个循环使用,我成功地获得了输出个体:

代码语言:javascript
复制
<xsl:for-each select="/item">
<xsl:value-of select="item_price*gst"/>
</xsl:for-each>

我的假设可能在某种程度上是这样的,但它似乎起作用了:

(谢谢你的帮助:)

EN

回答 1

Stack Overflow用户

发布于 2018-08-13 09:03:02

根据所使用的XSLT处理器的不同,XSLT1.0和XSLT2.0的解决方案不同。

XSLT1.0

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

代码语言:javascript
复制
<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>

XSLT2.0

对于XSLT2.0,使用sum(item/(item_price * gst))表达式计算产品之和是可以接受的。

代码语言:javascript
复制
<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作为

代码语言:javascript
复制
<sum>2300</sum>
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51816911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档