How does apply-templates work?
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 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-templatescalls thecdtemplate each time an element named"cd"is encountered.The
cdtemplate, in turn calls thetitleandartisttemplates to process the children elements of<cd>.titleis processed beforeartist. Note, that the order ofartistandtitleelements 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.
加载中,请稍侯......
精彩评论