I have just started learning XSL(T) and I wonder how apply-templates
work? I do not understand the recursively applies templates part of it as it is written in my b
You use <xsl:apply-templates>
to invoke the <xsl:template>
:s you have defined.
<xsl:apply-templates>
calls a matching template for each node in the set.
You can control processing order by specifying a select
attribute on apply-templates
.
See this example from w3schools:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
<xsl:template match="title">
Title: <span style="color:#ff0000">
<xsl:value-of select="."/></span>
<br />
</xsl:template>
<xsl:template match="artist">
Artist: <span style="color:#00ff00">
<xsl:value-of select="."/></span>
<br />
</xsl:template>
</xsl:stylesheet>
The first apply-templates
calls the cd
template each time an element named "cd"
is encountered.
The cd
template, in turn calls the title
and artist
templates to process the children elements of <cd>
.
title
is processed before artist
. Note, that the order of artist
and title
elements in the source XML makes no difference.
You could think of apply-templates
as analoguous to a subroutine call in procedural languages.
If you've read about apply-templates in a book but haven't understood it, then it's not clear that a few words here will help. Perhaps you need a different book: different tutorial styles appeal to different people. Or perhaps an online tutorial such as http://vimeo.com/15234803 will get the ideas across.
The essence of the template mechanism is that there are two parties involved. The xsl:apply-templates instruction selects some nodes for processing, and the template rules (between them) decide what that processing should be. This gives very loose coupling and great separation of concerns; it's rather like object-oriented message/method despatch, but much more flexible.
If you understand template rules you are done! Even if it's not that easy, they always give surprise. Read the specs.