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 book.
I understand the XPath-part of XSL(T) and so on but not what apply-templates
is doing and why I write it multiple times.
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 onapply-templates
.See this example from w3schools:
The first
apply-templates
calls thecd
template each time an element named"cd"
is encountered.The
cd
template, in turn calls thetitle
andartist
templates to process the children elements of<cd>
.title
is processed beforeartist
. Note, that the order ofartist
andtitle
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.