Skip to content

XSLT <xsl:template> Element

How the <xsl:template> element works in XSLT, including its syntax, attributes (name, match, priority, mode), and practical usage for transforming XML nodes into output.

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:

books.xmlxml
<?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>
books.xslxml
<?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>
Navigation