Sum of similar elements in XSLT

梦想与她 提交于 2019-12-25 06:58:11

问题


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>

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>

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

Can anybody please suggest how to achieve using XSLT ?


回答1:


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>



来源:https://stackoverflow.com/questions/37205574/sum-of-similar-elements-in-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!