<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

<xsl:template match="/">
  <html>
    <head>
      <title>Invoice</title>
    </head>
    <body>
      <h1>Invoice</h1>
      
      <!-- Format invoice items as a  table -->
      <table border="1" style="text-align: center">
        <tr>
          <th>Description</th>
          <th>Quantity</th>
          <th>Unit price</th>
          <th>Subtotal</th>
        </tr>
        <xsl:for-each select="invoice/item">
          <tr>
            <td><xsl:value-of select="description"/></td>
            <td><xsl:value-of select="qty"/></td>
            <td><xsl:value-of select="unitPrice"/></td>
            <td><xsl:value-of select="qty * unitPrice"/></td>
          </tr>
        </xsl:for-each>
        <tr>
          <th colspan="3">Total</th>
          <th>
            <!-- Call recursive summing template. We start with the first item -->
            <xsl:call-template name="add">
              <xsl:with-param name="node" select="invoice/item[1]"/>
            </xsl:call-template>
          </th>
        </tr>
      </table>
    </body>
  </html>
</xsl:template>
  
<!-- Recursive template. It will calculate total amount 
     from the all following items -->
<xsl:template name="add">
  <xsl:param name="node" select="."/>
  <xsl:variable name="sum-of-rest">
    <xsl:choose>
      <xsl:when test="$node/following-sibling::item">
        <xsl:call-template name="add">
          <xsl:with-param name="node"
            select="$node/following-sibling::item[1]"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>0</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:value-of select="($node/qty)*($node/unitPrice) + $sum-of-rest"/>  
</xsl:template>

</xsl:stylesheet>