Sorting with XSLT

Here should go questions about transforming XML with XSLT and FOP.
bushytop
Posts: 1
Joined: Mon Mar 23, 2009 7:32 pm

Sorting with XSLT

Post by bushytop »

I am trying to output a table which lists a customer's payments whilst keeping a running total. A section of my XML is as follows:

Code: Select all


<Accounts>
<Payment>
<CustomerID>1</CustomerID>
<Date>2009-03-16</Date>
<Amount>22</Amount>
</Payment>
<Payment>
<CustomerID>4</CustomerID>
<Date>2009-02-12</Date>
<Amount>35</Amount>
</Payment>
<Payment>
<CustomerID>2</CustomerID>
<Date>2009-05-17</Date>
<Amount>41</Amount>
</Payment>
I have included the following code to sort the output into date order:

Code: Select all

<xsl:apply-templates select="Payment">
<xsl:sort select="Date" />
</xsl:apply-templates>
In attempting to output the table I have written the following code:

Code: Select all

<td>
<xsl:apply-templates select="Date" />
</td>
<td>
<xsl:apply-templates select="Amount" />
</td>
<td>
<xsl:variable name="running-total" select="sum(preceding-sibling::Payment/Amount) + Amount)" />
<xsl:value-of select="$running-total" />
</td>
However, when accumulating the running total the calculations are done in the order of the xml output. How would I change this so that the calculations are done (and displayed) by the earliest date first??

Many Thanks
xml-looser
Posts: 1
Joined: Tue Jun 30, 2009 5:25 pm

Re: Sorting with XSLT

Post by xml-looser »

Code: Select all



<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="html"/>
<xsl:template match="/">
<xsl:apply-templates select="Accounts"/>
</xsl:template>
<xsl:template match="Accounts">
<html>
<table border="solid">
<tr>
<td>totalsum</td>
<td></td>
<td>
<xsl:value-of select="sum(//Amount)"/>
</td>
</tr>
<xsl:apply-templates select="Payment">
<xsl:sort data-type="number" select="substring(Date,1,4)"/>
<xsl:sort data-type="number" select="substring(Date,9,2)"/>
<xsl:sort data-type="number" select="substring(Date,6,2)"/>
</xsl:apply-templates>
</table>
</html>
</xsl:template>
<xsl:template match="Payment">
<tr>
<xsl:apply-templates select="Amount|Date|CustomerID"/>
</tr>
</xsl:template>
<xsl:template match="CustomerID">
<td>
<xsl:value-of select="."/>
</td>
</xsl:template>
<xsl:template match="Date">
<td>
<xsl:value-of select="."/>
</td>
</xsl:template>
<xsl:template match="Amount">
<td>
<xsl:value-of select="."/>
</td>
</xsl:template>
</xsl:stylesheet>
Post Reply