Outputting the Value of Something
Creating a simple text string is easy: we just use the <xsl:text> element. However, in any
stylesheet you write, you’ll probably need to output the value of
something from the XML source. That’s what the <xsl:value-of> element is for. In the example stylesheet we’re building, we
want to transform this element in the XML source:
<heading1>Generating text</heading1>
into this HTML element in the output:
<h2>Generating text</h2>
In other words, we want to take every <heading1> element and transform it
into an HTML <h2> element
that contains the value of the <heading1> element. Here’s a template
that does just that:
<xsl:template match="heading1">
<h2>
<xsl:value-of select="."/>
</h2>
</xsl:template>To generate our earlier paragraph that contains the number of
chapters, we’ll use <xsl:value-of> with the XPath count() function:
<p> This document contains <xsl:value-of select="count(/article/body/heading1)"/> chapters. </p>
This bit of XSLT creates the following HTML paragraph:
<p> This document contains 5 chapters. </p>
An HTML browser normalizes the whitespace before rendering it, as shown in Figure 4-1.

If we needed more control over the output, we could use <xsl:value-of> and <xsl:text> together:
<p> <xsl:text>This document contains </xsl:text> <xsl:value-of select="count(/article/body/heading1)"/> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access