打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
XSLT: Sum of products from multiple nodes

The XSL method sum(/foo) sums the value of all foo nodes in current context. If you, however, want to sum the product between two or more nodes the sum(/foo * /bar) is not sufficient as the product does not return a nodeset and thus sum() fails.

I found one way to sum products of multiple nodes and is to construct a temporary variable with the products, convert that variable to a nodeset and the sum all nodes in that temporary node set.

The function that converts a variable to a nodeset seems to be XSLT specific and the solution below is for Xalan since we are using it in our app. If you are using MSXML you will have to change the namespace but the name of the function is the same.

XML:
<Order>
    <OrderLine>
        <Quantity>
            <Amount>2</Amount>
        </Quantity>
        <Price>
            <UnitPrice>25</UnitPrice>
        </Price>
    </OrderLine>
    <OrderLine>
        <Quantity>
            <Amount>10</Amount>
        </Quantity>
        <Price>
            <UnitPrice>2</UnitPrice>
        </Price>
    </OrderLine>
    <OrderLine>
        <Quantity>
            <Amount>23</Amount>
        </Quantity>
        <Price>
            <UnitPrice>6</UnitPrice>
        </Price>
    </OrderLine>
</Order>

XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xalan="http://xml.apache.org/xalan">

    <xsl:template match="/Order">
    <root>
    <xsl:variable name="tmpTotal">
        <total_amount>
            <xsl:for-each select="OrderLine">
                <item>
                    <xsl:value-of select="Quantity/Amount * Price/UnitPrice"/>
                </item>
            </xsl:for-each>
        </total_amount>
    </xsl:variable>
        <total>
            <xsl:variable name="myTotal" select="xalan:nodeset($tmpTotal)"/>
            <xsl:value-of select="sum($myTotal/total_amount/item)" />
        </total>
    </root>
    </xsl:template>
</xsl:stylesheet>



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
XSLT来总结的两个属性的产品
What is Average Variable Cost
【图】短线拐点
再谈ETL之一(原)
DAX:【翻译】SUMMARIZE的秘密
变量英语
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服