In this concluding article, expand your XSLT vocabulary by exploring conditional constructs, loops, variables, and numbering, together with examples and illustrations of how these programming capabilities can substantially simplify your XSLT experience.
XSLT also comes with a bunch of instructions designed to help authors create nodes in the result tree using XSLT instructions, rather than literal character data. These come in particularly handy when elements, attributes, PIs or text strings need to be generated dynamically.
In order to illustrate this, let's consider a small snippet from the stock data you just saw:
The <xsl:element> instruction is used to create a new element in the result
tree; the name of the element to be created is specified via the "name" attribute. In case the element name needs to be generated dynamically - as in the above example, where the element name depends on the stock symbol - an expression can be used, enclosed within curly braces.
In the example above, the elements to be created are "empty" elements - that is, they do not enclose any content. In case I wanted to add some content between the opening and closing tags, I would use the following instruction:
If you take a close look at the first template rule above, you'll see that I've
actually used this technique when creating the outermost "portfolio" element.
Once an element has been created, it may be necessary to assign it some attributes - this is accomplished via the <xsl:attribute> instruction. The syntax here is similar to that of <xsl:element>, although <xsl:attribute> instructions must always be contained within either literal or dynamically-created parent elements.
As you may have guessed, XSLT doesn't just restrict you to creating elements and attributes dynamically - you can also create text nodes, PIs and comments, using the <xsl:text>, <xsl:processing-instruction> and <xsl:comment> instructions respectively. Take a look at the following examples, which demonstrate how this works:
Superman was here!
Mary had a little lamb
<xsl:processing-instruction name="bite_me" />
Obviously, text, comments and PIs can also be generated dynamically, as previously
demonstrated with elements and attributes.