Chapter 4 - Templates Rule! | |
XSLT For Dummies | |
by Richard Wagner | |
Hungry Minds 2002 |
So far in this chapter, I have been using examples that have had only a single template rule within the stylesheet. You can combine template rules in the same stylesheet, which is actually standard practice. However, suppose the processor evaluates a node in the source tree and finds that two or more of the template rules match. Which of the matches wins? XSLT prioritizes template rules based on a fairly complex system of weighting , but Table 4-3 shows the more common cases (where Level 1 is highest priority, Level 4 is lowest ):
Technical Stuff You can override the XSLTs built-in prioritization scheme by explicitly declaring your own priority for a template rule. You do this by using the priority attribute. To illustrate , suppose I use the score.xml file (refer to Listing 4-1) as the source document and then want to apply the following XSLT stylesheet: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" omit-xml-declaration="yes"/> <xsl:template match="score"> Almost: <xsl:apply-templates select="film"/> </xsl:template> <xsl:template match="score[@id='1']"> The Best: <xsl:apply-templates select="film"/> </xsl:template> </xsl:stylesheet> The first template rule returns a match when the current node has a score element node as a child. The second template rule returns a match when the current node has a score element node with an id attribute that equals 1 . So, when the source tree is evaluated, the XSLT processor finds two template rules that match when the current node is found to have a score element node with an id attribute equaling 1 . However, the second template rule, being more specific to this particular node, is considered higher in priority; therefore, the node is matched to the second template rule, not the first. The result document looks like the following text output: The Best: A Little Princess Almost: Chocolat Almost: Vertigo Almost: Field of Dreams Almost: Dead Again
|