Skip to main content

XSLT <xsl:apply-template> Element

The <xsl:apply-templates> element applies a template rule to the current element or the current element's child nodes.

<xsl:apply-template> Element

Syntax

The syntax of <xsl:apply-template> is as follows:

<xsl:apply-template 
select=Expression
mode=QName >
</xsl:apply-template>

Attributes

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

NameDescription
selectUsed to process nodes selected by an XPath expression, instead of processing all the children.
modeAllows an element as specified by its Qualified Names to be processed multiple times, each time producing a different result.

Example

Let's see an example:

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>
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"/>
<xsl:apply-templates select="price"/>
</p>
</xsl:template>

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

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

<xsl:template match="price">
Price: <span style="color:#0000ff">
<xsl:value-of select="."/></span>
<br />
</xsl:template>

</xsl:stylesheet>
note

If we add a "select" attribute to the <xsl:apply-templates> element, it will only process child elements that match the value of the attribute.

We can use the "select" attribute to specify in which order the child nodes should be processed.