XSL Basics (part 1) - Up A Tree (
Page 3 of 6 )
An XSLT transformation essentially
consists of converting an XML "source tree" into a new - and usually completely
different - "result tree". This is accomplished by means of an XSLT stylesheet,
which contains one or more template rules. A template rule performs two functions:
it first identifies a pattern to match in the source tree, and then describes
the structure of the desired result tree. It is this process of transforming -
or as Calvin would say, transmogrifying - the source tree into the result tree
that gives XSLT its name.
Consider the following example:
<xsl:template match="/">
My name is <xsl:value-of select="name" />
</xsl:template>
In this case, the template rule matches the root of the XML source tree, looks
for the "name" element and print a string containing the value of that element.
The body of a template rule may contain a sequence of character data, which is
reproduced as is, and/or XSLT processing instructions, which are executed by the
processor. For example, the following template rule contains an XSLT processing
instruction to loop a certain number of times, enclosed within non-XSLT text fragments.
<xsl:template match="/list">
<xsl:for-each select="item">
Item: <xsl:value-of
select="."/><br/>
</xsl:for-each>
</xsl:template>
An XSLT stylesheet may contain one or more template rules. Each rule typically
applies to a specific node (or set of nodes) in the source tree, executes a set
of instructions to create the structure of the corresponding node(s) in the result
tree, and also specifies whether processing should continue recursively (to the
children of the current node) or stop at that point itself.
In case processing is to continue recursively, the XSLT processor looks for a
template rule matching the next element in the source tree, creates the corresponding
result tree fragment, and continues recursively until it runs out of nodes or
template rules. The end-product is thus the result of interaction between different
template rules.
In case more than one template rule matches a specific element in the source
tree, XSLT conflict resolution states that the most specific rule is applied.
You'll see an example of this a little further down.