Matchmaker, Make Me a Match

 
xslt for dummies
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 ):

Table 4-3: Priority of Common Template Rules

Level

Description of Rule

Example

1 (most specific)

Element name with a filter

<xsl:template match= "score[@id='1']">

1

Element as part of a path

<xsl:template match= "scores/score">

2

Element name

<xsl:template match= "score">

3

Node test

<xsl:template match= "node()"> or <xsl: template match="*">

4

Built-in template rule

<xsl:template match="*/">

 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 
  
 
 
2000-2002    Feedback


XSLT For Dummies
XSLT for Dummies
ISBN: 0764536516
EAN: 2147483647
Year: 2002
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net