Create a table with calculation
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://java2s.com/XSLT/functions">
<xsl:template match="/">
<html>
<body>
<h3>
Customer
<xsl:value-of select="Orders/@CustomerId" />
</h3>
<table>
<thead>
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Order Total</th>
</tr>
</thead>
<tbody>
<xsl:apply-templates select="Orders/Order">
<xsl:sort
select="translate(@OrderDate, '-', '')" data-type="number" />
</xsl:apply-templates>
</tbody>
</table>
</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://java2s.com/XSLT/functions">
<body>
<h3>
Customer
1
</h3>
<table>
<thead>
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Order Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>ord2</td>
<td>2006-10-30</td>
<td>14.5</td>
</tr>
<tr>
<td>ord1</td>
<td>2008-09-01</td>
<td>8</td>
</tr>
</tbody>
</table>
</body>
</html>
Related examples in the same category