A Simple Technique for Adding Whitespace to Text Output

Whenever we generate text output, we usually need to control line breaks. Programming languages have facilities for this; in Java, for example, we can use System.out.print(), System.out.println(), or even System.out.print("\n\n") to put line breaks exactly where we need them.

The simplest way to do this in an XSLT stylesheet is to use the character entities for the newline (&#xA;) and tab (&#x9;) characters. We’ve used this technique with the newline character throughout this chapter. As a further example, here’s a stylesheet that uses all three character entities in the separator attribute of the <xsl:value-of> element:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>&#xA;Values separated with newlines:&#xA;&#xA;</xsl:text>
    <xsl:value-of select="1 to 7" separator="&#xA;"/>

    <xsl:text>&#xA;&#xA;Values separated with tabs:&#xA;&#xA;</xsl:text>
    <xsl:value-of select="1 to 7" separator="&#x9;"/>

    <xsl:text>&#xA;&#xA;Values separated with spaces:&#xA;&#xA;</xsl:text>
    <xsl:value-of select="1 to 7" separator="&#x20;"/>
  </xsl:template>

</xsl:stylesheet>

This stylesheet generates these results:

Values separated with newlines:

1
2
3
4
5
6
7

Values separated with tabs:

1       2       3       4       5       6       7

Values separated with spaces:

1 2 3 4 5 6 7

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.