With a sound foundation in XML theory behind you, it's now time to address the other half of the jigsaw - actually converting all that marked-up data into something useful. This first article in a two-part series examines the need, rationale and basic concepts of XSLT, the Extensible Stylesheet Language for Transformations, with sample code and examples.
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:
My name is <xsl:value-of select="name" />
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.
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.