However, one of the things a template can do is change the order of
traversal. That is, it can specify which element(s) should be
processed next. It can specify that an element(s) should be processed
in the middle of processing another element. It can even prevent
particular elements from being processed. In fact, Examples 8-4
through 8-6 all implicitly prevent the child elements of each
person element from being processed. Instead, they
provided their own instructions about what the XSLT processor was and
was not to do with those children.
The xsl:apply-templates element lets you make
explicit your choice of processing order. Its
select attribute contains an XPath expression
telling the XSLT processor which nodes to process at that point in
the output tree.
For example, suppose you wanted to list the names of the people in
the input document; however, you want to put the last names first,
regardless of the order in which they occur in the input document,
and you don't want to output the professions or
hobbies. First you need a name template that looks like this:
<xsl:template match="name">
<xsl:value-of select="last_name"/>,
<xsl:value-of select="first_name"/>
</xsl:template>
However, this alone isn't enough; if this were all
there was in the stylesheet, not only would the output include the
names, it would also include the professions and hobbies. You also
need a person template rule that says to apply templates to
name children only, but not to any other child
elements like profession or
hobby. This template rule does that:
<xsl:template match="person">
<xsl:apply-templates select="name"/>
</xsl:template>
The order of the template rules in the stylesheet
doesn't matter. It's only the order
of the elements in the input document that matters.
Applying templates is also important when the child elements have
templates of their own, even if you don't need to
reorder the elements. For example, let's suppose you
want a template rule for the root people element
that wraps the entire document in an HTML header and body. Its
template will need to use xsl:apply-templates to
indicate where it wants the children of the root element to be
placed. That template rule might look like this: