首页 > 解决方案 > 如何计算 XSLT 1.0 中每个单元分组的节点总和?

问题描述

我想用 XSLT1.0 根据 XML 中的节点计算 XML 值的总和。我需要@QtyRoutes 表中所有可用值的总和。每个OrderTransfrom Routes 都有一个itedID, 将匹配itemIDfrom Products。Products 表也有ItemDetails节点,每个产品都有一个unitID. 我的最终结果应该显示所有@Qty分组的总和@unitID

以下是 XML 源代码:

<root>
    <Routes>
        <OrderTrans itemID="1">
            <View Qty="5.00"/>
        </OrderTrans>
        <OrderTrans itemID="2">
            <View Qty="200.00"/>
        </OrderTrans>
        <OrderTrans itemID="2">
            <View Qty="10.00"/>
        </OrderTrans>
        <OrderTrans itemID="1">
            <View Qty="20.00"/>
        </OrderTrans>
    </Routes>
    <Products>
        <Product itemID="2">
            <ItemDetails unitID="KG"/>
        </Product>
        <Product itemID="1">
            <ItemDetails unitID="Pcs"/>
        </Product>
    </Products>
</root>

这是我尝试过的一个片段:

<xsl:key name="groupkey" match="/root/Products/Product/ItemDetails" use="@unitID"/>
<xsl:template>
    <xsl:for-each select="/root/Products/Product/ItemDetails[generate-id(.) = generate-id(key('groupkey',@unitID)[1])]">
        <fo:block>Sum here:
            <xsl:value select="sum(../../../Routes/OrderTrans/View/@Qty[@unitID = current()/@unitID])">
        </fo:block>
    </xsl:for-each>
</xslt:template>

结果应该是:

Sum here: 25.00 Pcs. 210.00 KG

标签: xmlxsltxslt-1.0

解决方案


当您已经为每个产品拥有一个唯一节点时,我不明白为什么需要对任何东西进行分组。你可以简单地做:

<xsl:key name="order" match="OrderTrans" use="@itemID"/>

<xsl:template match="/root">
    <your-root-here>
        <xsl:for-each select="Products/Product">
            <fo:block>
                <xsl:text>Sum here: </xsl:text>
                <xsl:value-of select="sum(key('order', @itemID)/View/@Qty)"/>
                <xsl:text> </xsl:text>
               <xsl:value-of select="ItemDetails/@unitID"/>
            </fo:block>
        </xsl:for-each>
    </your-root-here>
</xsl:template>

推荐阅读