XSLT 中相似元素的总和 [英] Sum of similar elements in XSLT

查看:34
本文介绍了XSLT 中相似元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到输入 xml 为:

I get input xml as :

 <root>
<SalesOrderLine>
<Item><ID>1056365</ID></Item>
<Quantity>1.00</Quantity>
<UnitPrice><UnitAmount>4.4</UnitAmount></UnitPrice>
</SalesOrderLine>
<SalesOrderLine>
<Item><ID>1056365</ID></Item>
<Quantity>1.00</Quantity>
<UnitPrice><UnitAmount>8.4</UnitAmount></UnitPrice>
</SalesOrderLine>
<SalesOrderLine>
<Item><ID>1056366</ID></Item>
<Quantity>1.00</Quantity>
<UnitPrice><UnitAmount>0.00</UnitAmount></UnitPrice>
</SalesOrderLine>
</root>

预期的输出 xml 是:

The expected output xml is :

<root1>
<SL>
<Item><ID>1056365</ID></Item>
<Quantity>2.00</Quantity>
<UnitPrice><UnitAmount>6.4</UnitAmount></UnitPrice>
</SL>
<SL>
<Item><ID>1056366</ID></Item>
<Quantity>1.00</Quantity>
<UnitPrice><UnitAmount>0.00</UnitAmount></UnitPrice>
</SL>
</root>

行数量=总和(具有相同商品ID的行数量)行数量 = sum(行数量 * 行价格)/sum(具有相同商品 id 的行数量)

line quantity = sum (line quantity with same item id) line amount = sum (line quantity * line price) / sum (line quantity with same item id)

有人可以建议如何使用 XSLT 实现吗?

Can anybody please suggest how to achieve using XSLT ?

推荐答案

我相信这就是您正在寻找的 XSL.它使用 for-each-group 中的变量来计算每个销售订单行的实际总数(即其数量乘以单价).然后将该变量相加并除以数量总和,以正确计算整体单价.

I believe this is the XSL you're looking for. It uses a variable inside the for-each-group to calculate each Sales Order Line's actual total (i.e. its quantity times its unit price). That variable is then summed and divided by the quantity sum to properly calculate the overall unit price.

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="root">
    <root1>
        <xsl:for-each-group select="SalesOrderLine" group-by="Item/ID">
            <xsl:variable name="QuantitySum" select="sum(current-group()/Quantity)"/>
            <xsl:variable name="SLTotals">
                <xsl:for-each select="current-group()">
                    <SLTotal><xsl:value-of select="Quantity * UnitPrice/UnitAmount"/></SLTotal>
                </xsl:for-each>
            </xsl:variable>
            <SL>
                <Item>
                    <ID>
                        <xsl:value-of select="current-grouping-key()"/>
                    </ID>
                </Item>
                <Quantity>
                    <xsl:value-of select="$QuantitySum"/>
                </Quantity>
                <UnitPrice>
                    <UnitAmount>
                        <xsl:value-of select="sum($SLTotals/SLTotal) div $QuantitySum"/>
                    </UnitAmount>
                </UnitPrice>
            </SL>
        </xsl:for-each-group>
    </root1>
</xsl:template>

这篇关于XSLT 中相似元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆