1

我需要按日期对以下交易进行分组,并计算每个日期的所有交易的总和和数量。

输入:

<transactions>
<transaction id="1">
    <element key="2" name="Amount">3.00</element>
    <element key="3" name="Date">01.01.2010</element>
</transaction>  
<transaction id="2">
    <element key="2" name="Amount">4.00</element>
    <element key="3" name="Date">01.01.2010</element>
</transaction>  
<transaction id="3">
    <element key="2" name="Amount">5.00</element>
    <element key="3" name="Date">01.01.2011</element>
</transaction>  
<transaction id="4">
    <element key="2" name="Amount">6.00</element>
    <element key="3" name="Date">01.01.2011</element>
</transaction>  

期望的输出:

<transactions>
<date value="01.01.2010">
    <sum>7.00</sum>
    <numberOfTrans>2</numberOfTrans>
    <transaction id="1">
        <element key="2" name="Amount">3.00</element>
    </transaction>  
    <transaction id="2">
        <element key="2" name="Amount">4.00</element>
    </transaction>
</date>
<date value="01.01.2011">
    <sum>11.00</sum>
    <numberOfTrans>2</numberOfTrans>
    <transaction id="3">
        <element key="2" name="Amount">5.00</element>
    </transaction>  
    <transaction id="4">
        <element key="2" name="Amount">6.00</element>
    </transaction>
</date>

如何使用 XSLT 1.0 做到这一点?

谢谢!

4

1 回答 1

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

   <xsl:key name="groups" match="/transactions/transaction" use="element[@name='Date']" />

   <xsl:template match="/transactions">
      <transactions>
         <xsl:apply-templates select="transaction[generate-id(.) = generate-id(key('groups', element[@name='Date'])[1])]" />
      </transactions>
   </xsl:template>

   <xsl:template match="transaction">
      <date id="{element[@name='Date']}">
         <sum>
            <xsl:value-of select="format-number(sum(key('groups', element[@name='Date'])/element[@name='Amount']), '#.00')" />
         </sum>
         <numberOfTrans>
            <xsl:value-of select="count(key('groups', element[@name='Date']))" />
         </numberOfTrans>
         <xsl:for-each select="key('groups', element[@name='Date'])">
            <xsl:copy>
               <xsl:copy-of select="@*" />
               <xsl:copy-of select="element[@name='Amount']" />
            </xsl:copy>
         </xsl:for-each>
      </date>
   </xsl:template>
</xsl:stylesheet>
于 2013-10-08T16:27:35.820 回答