Skip to main content

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.


The syntax of <xsl:template> is as follows



The table describes the meaning of the attributes of <xsl:template>:

nameName of the element on which template is to be applied.
matchPattern which signifies the element(s) on which template is to be applied.
priorityPriority number of a template. Matching template with low priority is not considered in from in front of high priority template.
modeAllows element to be processed multiple times to produce a different result each time.


Let's see an example:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="">

<xsl:template match="/">
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<xsl:for-each select="bookstore/book">
<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>


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.