Initial Example for Named Templates
This example creates a standard simple table. The XSLT file does not yet use named templates. The subsequent topics in this section add named templates, resulting in the Finished Example for Named Templates.
Example
This example contains an XML file, and an XSLT file to transform it. The result is a simple series of headings and tables for the individual regions. This table shows data for each sales region, but not for all regions together.
XML File (region_qtr.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="region_qtr.xsl" ?> <sales quarter="2001-01-01"> <region> <name>Northeast</name> <manager>Kim Abercrombie</manager> <units>9881</units> <sales_amt curr="">150680.89</sales_amt> </region> <region> <name>Southeast</name> <manager>Jeff D. Henshaw</manager> <units>4329</units> <sales_amt curr="">67015.48</sales_amt> </region> <region> <name>Southwest</name> <manager>Sunil Koduri</manager> <units>3543</units> <sales_amt curr="">57029.25</sales_amt> </region> <region> <name>Northwest</name> <manager>Brad Sutton</manager> <units>7569</units> <sales_amt curr="">127423.90</sales_amt> </region> </sales>
XSLT File (region_qtr.xsl)
<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/TR/REC-html40" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>Quarterly Sales (Quarter Beginning <xsl:value-of select="sales/@quarter"/>) </title> <style type="text/css"> h1 {background-color: teal; font-family: Tahoma,Verdana,Arial,sans-serif; font-size: 24pt} h2 {background-color: yellow; font-family: Tahoma,Verdana,Arial,sans-serif; font-size: 18pt} h3 {background-color: white; font-family: Tahoma,Verdana,Arial,sans-serif; font-size: 14pt; font-weight: bold} th {background-color: silver; font-family: Tahoma,Verdana,Arial,sans-serif} td {background-color: white; font-family: Tahoma,Verdana,Arial,sans-serif} .page {width: 75%} </style> </head> <body> <div class="page"> <xsl:apply-templates/> </div> </body> </html> </xsl:template> <xsl:template match="sales"> <h1>Quarterly Sales by Region</h1> <h2>Quarter Beginning <xsl:value-of select="@quarter"/></h2> <xsl:apply-templates/> </xsl:template> <xsl:template match="region"> <h3> <xsl:value-of select="name"/> Region (Manager: <xsl:value-of select="manager"/>) </h3> <table width="100%"> <tr> <th># Units</th> <th>Qtr Sales Amount</th> <th>Amt/Unit</th> </tr> <tr> <td width="33%" align="right"> <xsl:value-of select="format-number(units, '#,##0')"/> </td> <td width="33%" align="right"> <xsl:value-of select="format-number(sales_amt, '#,##0.00')"/> </td> <td align="right"> <xsl:value-of select="format-number(sales_amt div units, '#,##0.000')"/> </td> </tr> </table> </xsl:template> </xsl:stylesheet>
Formatted Output