XSLT用于分组和求和值

时间:2013-02-27 12:46:16

标签: xml xslt xslt-2.0

我是XSLT的新手,我很难完成一个结果,所以我来这里以防有人可以帮助我。

我有以下XML:

<funds>
    <bags>
        <bag name="BAG_USD_MAIN" value="10.0" type="USD">
            <pockets>
                <pocket name="bank" value="7.5">
                <pocket name="award" value="2.5">
            </pockets>
         </bag>
        <bag name="BAG_USD_SAVINGS" value="290.75" type="USD">
            <pockets>
                <pocket name="bank" value="290.75">
            </pockets>
         </bag>
        <bag name="BAG_EUR_EXTRA" value="890.0" type="EUR">
            <pockets>
                <pocket name="bank" value="753.0">
                <pocket name="bank_eng" value="137.0">
            </pockets>
         </bag>
    </bags>
 </funds>

我希望能够以这种方式改变它:

<result>
    <total type="USD">375.0</total>
    <total type="EUR">890.0</total>
</result>

是否可以使用XSLT?

谢谢你, 问候 TS

2 个答案:

答案 0 :(得分:2)

因为您使用的是 XSLT 2.0 ,所以您可以使用&lt; xsl:for-each-group&gt;元素按@type对元素进行分组,然后使用sum()对组中的元素求和。

以下样式表解决了您要执行的操作:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>


    <!-- Match the bags element  -->
    <xsl:template match="bags">
        <result>
            <!-- Group each bag element by its type -->
            <xsl:for-each-group select="bag" group-by="@type">
                <!-- Use the current key to display the type attribute -->
                <total type="{current-grouping-key()}">
                    <!-- Sum all the elements from the current group -->
                    <xsl:value-of select="sum(current-group()/@value)" />
                </total>
            </xsl:for-each-group>
        </result>
    </xsl:template>

</xsl:stylesheet>

为了完整起见, XSLT 1.0 解决方案将基于Muenchian Grouping。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <!-- Index all bag elements withing bags element using their
         type attribute by using a key -->
    <xsl:key name="currency-key"
             match="/funds/bags/bag"
             use="@type" />

    <!-- Match bags element -->
    <xsl:template match="bags">
        <result>
            <!-- Match the first bag element for a specific group -->
            <xsl:apply-templates select="bag[generate-id() = generate-id(key('currency-key', @type)[1])]" />
        </result>
    </xsl:template>

    <xsl:template match="bag">
        <total type="{@type}">
            <!-- Sum all the elements from the @type group -->
            <xsl:value-of select="sum(key('currency-key', @type)/@value)" />
        </total>
    </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:0)

是。我没有方便的XSLT处理器,但尝试类似以下内容:

<result>
  <xsl:for-each select="distinct-values(//bag/@type)">
    <total type="."><xsl:value-of select="sum(//bag[@type = .])"/></total>
  </xsl:for-each>
</result>

对于大量数据,您应该考虑改为使用<xsl:for-each-group>