XML/XSLT stylesheet/sum
Create a table with calculation
<source lang="xml">
File: Data.xml <?xml version="1.0"?> <Orders CustomerId="1">
<Order OrderId="ord1" OrderDate="2008-09-01"> <Items> <Item ItemId="a1" Quantity="1" ItemPrice="2.00"></Item> <Item ItemId="b2" Quantity="1" ItemPrice="3.00"></Item> <Item ItemId="c3" Quantity="2" ItemPrice="1.50"></Item> </Items> </Order> <Order OrderId="ord2" OrderDate="2006-10-30"> <Items> <Item ItemId="a1" Quantity="2" ItemPrice="2.00"></Item> <Item ItemId="d4" Quantity="2" ItemPrice="1.00"></Item> <Item ItemId="e5" Quantity="1" ItemPrice="3.50"></Item> <Item ItemId="h8" Quantity="1" ItemPrice="5.00"></Item> </Items> </Order>
</Orders> File: Transform.xslt <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:udf="http://wbex.ru/XSLT/functions"> <xsl:template match="/"> <html> <body>
Customer <xsl:value-of select="Orders/@CustomerId" />
Order ID | Order Date | Order Total |
---|
</body> </html> </xsl:template> <xsl:template match="Order"> <tr> <td> <xsl:value-of select="@OrderId" /> </td> <td> <xsl:value-of select="@OrderDate" /> </td> <td> <xsl:value-of select="udf:get-order-total(Items)" /> </td> </tr> </xsl:template> <xsl:function name="udf:get-order-total" as="xs:double"> <xsl:param name="items" /> <xsl:value-of select="sum(for $item in $items/Item return $item/@Quantity * $item/@ItemPrice)" /> </xsl:function>
</xsl:stylesheet> Output: <html xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:udf="http://wbex.ru/XSLT/functions">
<body>
Customer 1
Order ID | Order Date | Order Total |
---|---|---|
ord2 | 2006-10-30 | 14.5 |
ord1 | 2008-09-01 | 8 |
</body>
</html>
</source>