Creating Simple Text

There are many times you need to write some text to the output. In the first example we’ll build in this chapter, we want to create HTML that looks like this:

<h1>Table of Contents</h1>
<h2>Generating text</h2>
<h2>Numbering things</h2>
<h2>Formatting numbers</h2>
<h2>Copying nodes from the input document to the output</h2>
<h2>Handling whitespace</h2>

In this output document, the text of each item in the table is the text of a particular element in the XML source. The text Table of Contents, however, is the same each time. To generate this text, we’ll use the <xsl:text> element. We’ll start our stylesheet by generating that text:

<xsl:template match="/">
  <h1>
    <xsl:text>Table of Contents</xsl:text>
  </h1>
  ...
</xsl:template>

All we did here was insert a string in our output document. To make things even simpler, we could have done this:

<xsl:template match="/">
  <h1>Table of Contents</h1>
  ...
</xsl:template>

For any non-XSLT element in a stylesheet (<h1>, for example), XSLT’s default behavior is to simply pass that element to the output. Normally we’ll use <xsl:text> when we need complete control over whitespace or when we’re creating text output instead of a marked-up document such as an HTML file.

In these examples, we simply wrote text to our output document; most often we’ll combine text with values from our source document. For example, we might want to generate an HTML document that looks like this:

<h1>Table of Contents</h1> <p>This document contains <b>5</b> chapters:</p> ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.