Skip to main content

XSLT <xsl:template>

XSLT <xsl:template>

The <xsl:template> element contains rules to apply when a specified node is matched.

The match attribute is used to associate the template with an XML element. The match attribute can also be used to define a template for a whole branch of the XML document (i.e. match="/" defines the whole document).

note

<xsl:template> is a top-level element.

Syntax

<xsl:template
name="name"
match="pattern"
mode="mode"
priority="number">

<!-- Content:(<xsl:param>*,template) -->

</xsl:template>

Attributes

AttributeValueRequired/OptionalDescription
namenameOptionalSpecifies a name for the template.

Note: If this attribute is omitted there must be a match attribute
matchpatternOptionalThe match pattern for the template.

Note: If this attribute is omitted there must be a name attribute
modemodeOptionalSpecifies a mode for this template
prioritynumberOptionalA number which indicates the numeric priority of the template

Example

Consider the XML document about a bookstore shown below:

books.xml
<?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>

We want to list title and author of each book:

books.xsl
<?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>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="book">
<p>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="author"/>
</p>
</xsl:template>

<xsl:template match="title">
Title: <span style="color:#ff0000">
<xsl:value-of select="."/></span>
<br />
</xsl:template>

<xsl:template match="author">
Author: <span style="color:#00ff00">
<xsl:value-of select="."/></span>
<br />
</xsl:template>

</xsl:stylesheet>