XSLT <xsl:template>
Element
An XSL style sheet consists of one or more set of rules that are called templates.
A template contains rules to apply when a specified node is matched.
<xsl:template>
Element
<xsl:template>
element is used to build templates. It defines a way to reuse templates in order to generate the desired output for nodes of a particular type/context.
Syntax
The syntax of <xsl:template>
is as follows
<xsl:template
name=Qname
match=Pattern
priority=number
mode=QName>
</xsl:template>
Attributes
The table describes the meaning of the attributes of <xsl:template>
:
Name | Description |
---|---|
name | Name of the element on which template is to be applied. |
match | Pattern which signifies the element(s) on which template is to be applied. |
priority | Priority number of a template. Matching template with low priority is not considered in from in front of high priority template. |
mode | Allows element to be processed multiple times to produce a different result each time. |
Example
Let's see an example:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<year>2022</year>
<price>39.99</price>
</book>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>
</bookstore>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Price</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="year"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The <xsl:stylesheet>
element defines that this document is an XSLT style sheet document (along with the version number and XSLT namespace attributes).
The <xsl:template>
element defines a template and the content inside the <xsl:template>
element defines some HTML to write to the output.
The match="/"
attribute associates the template with the root of the XML source document.
In the example, <xsl:value-of>
element is used to select values from the XML elements.
You can learn more in the XSLT value-of chapter.