XSLT » Elements » xsl:apply-templates


The xsl:apply-templates element defines a set of nodes to be processed, or by default selects all child nodes of the current node being processed, and finds a matching template rule to apply to each node in the set. Since each node in the node set is treated individually, it is possible for each node to have a different template applied to it. Note that a template rule is not actually returned, but rather, it manifests itself by how the node is displayed in the output.

There are only two possible procedures by which a template rule can be chosen for a node. If the node matches the pattern defined by the match attribute of an xsl:template element, then that template will be applied. If more that one such match occurs, then the template with the highest priority will be applied. Or if the priorities are the same, the last template encountered with that priority will be applied. If there are no templates, or a match cannot be found, then the XSLT processor will apply a built-in template rule.
The xsl:apply-templates element can only contain the xsl:sort or xsl:with-param elements. By default the nodes will be assigned templates in the order that they occur. However, if there are one or more xsl:sort instructions, then the nodes will be sorted before the templates are assigned. The actual assignment of a template to a specific individual node is not dependent on the sorting order. The xsl:with-param element defines parameters that will be applied to the template rules.
This is not a self-closing element. The separate closing element is mandatory.


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="devguru_staff/programmer>
<xsl:apply-templates select="name" />
<xsl:apply-templates select="dob" />
<xsl:apply-templates select="age" />
<br />

<xsl:template match="name">
<span style="font-size=22px;">
<xsl:value-of select="." />
<br />

<xsl:template match="dob">
DOB:<span style="color:blue;">
<xsl:value-of select="." />
<br />

<xsl:template match="age">
AGE:<span style="color:green;">
<xsl:value-of select="." />
<br />

Bugs Bunny
DOB: 03/21/1970
AGE: 31

Daisy Duck
DOB: 08/09/1949
AGE: 51

Minnie Mouse
DOB: 04/13/1977
AGE: 24

DOB: 07/04/1979
AGE: 21

Porky Pig
DOB: 11/30/1956
AGE: 44

Road Runner
DOB: 01/19/1953
AGE: 48

We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_applytemplates.xsl"?>
and we name it: xslt_example_applytemplates.xml In this example we create three different templates and apply them in the desired order in a fourth template using the xsl:apply-templates element.

This is the code for xslt_example_applytemplates.xml.

Language(s): XSLT

See Also: