Outputting Markup

In the stylesheet shown in Example 5.1, “A simple XSLT stylesheet for jokebook (excerpt)”, each template (i.e. within the <xsl:template> elements) could also include XHTML markup, since that's what we're outputting to our result document in this case.

The template for 'jokebook', which is the root element of our XML file in each case, is defined first.

  <xsl:template match="jokebook">
	<html>
	  <head>
		<title>My Jokes</title>
	  </head>
	  <body>
		<h1>My Jokes</h1>
		<xsl:apply-templates />
	  </body>
	</html>
  </xsl:template>
   

Here, we're adding some structural XHTML markup which will form the basis of the XHTML result document, and in the midst of this asking the processor to apply any relevant templates for the contents of the <jokebook> tag, which is achieved with the <xsl:apply-templates /> element.

Skip down now to the <double-entendre> template:

  <xsl:template match="double-entendre">
	<h3>Double-entendre:</h3>
	<p>The phrase 
	  <xsl:value-of select="phrase" />
	  can mean:</p>
	<ol>
	  <xsl:for-each select="meaning">
		<li><xsl:value-of /></li>
	  <xsl:for-each />
	</ol>
  </xsl:template>
 

This again outputs some HTML, but then outputs the entire contents of the <phrase> tag using a <xsl:value-of> statement. Note that this will output the whole of the contents of the element specified, so if it contains sub-elements, you'll get the values of all the #PCDATA elements with no surrounding tags splurged into the output.

You can also see an <xsl:for-each> statement which processes each of the <meaning> tags in the structure. We could, in fact, create a new template for <meaning> and do an <xsl:apply-templates>, which would work just as well here. However, sometimes we need to keep count of how many meanings we've processed (say we wanted to print the total number of meanings at the end), and using the <xsl:for-each> will allow us to do this.

The <xsl:value-of /> without a select attribute just means 'output the value of the current node', in this case, the whole of the currently processed <meaning> tag.

There are a number of other processing elements which can be used, together with a way of defining variables for temporarily storing values, which we'll look at in detail next time.

[Important] Hints and Gotchas

As the stylesheet must be well-formed XML, we have to use XHTML-style closing tags to all our HTML markup.

Though it's common to do so, it's not necessary to create a template for every element you've defined in your DTD.

If a template can't be found for a node in the document tree, then the default action is to apply-templates to its contents, or to output the contents if it's a #PCDATA node.

Order of definitions isn't important, except for your own sanity!