XML technologies / XSLT / XSLT Cookbook / From XML to text / Handling whitespace

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You need to convert XML into formatted text, but whitespace problems spoil the results.

Solution

Consider this annotated XML. Symbols ↵ (newline), → (tab) and ❑ (space) mark whitespace-only nodes that are often overlooked yet copied into the output:

<review>↵
→<author>↵
→→ <name>Sal Mangano</name>↵
→→<email>smangano@somewhere.com</email>↵
→</author>↵
<title>XSLT Kochbuch</title>↵
<reviewer>↵
→→<name>❑<anonymous/>❑</name>↵
→→<email>smangano@somewhere.com</email>↵
→→<comment>↵
Absolut brillant. <b>Jeden Cent wert!</b>❑<i>Müssen Sie kaufen, weil ich ↵
den Autor persönlich kenne und er das Geld sicher gebrauchen kann.</i>↵
→→</comment>↵
→ </reviewer>↵
</review>↵

Too much whitespace

  1. Use xsl:strip-space to remove whitespace-only nodes.

    This top-level element has a single attribute, elements, assigned a whitespace-separated list of element names from which to remove excess whitespace. Here, excess whitespace means text nodes containing only whitespace. For example, whitespace separating words in the illustrated comment element matters because its content is not exclusively whitespace. In contrast, the specially marked whitespace forms whitespace-only nodes.

    A common idiom uses <xsl:strip-space elements="*"/> to strip whitespace by default and xsl:preserve-space to override this for specific elements (see below). In XSLT 2.0 you can use elements="*:Name" to strip whitespace from all elements with that local name, regardless of namespace.

  2. Use normalize-space to remove excess whitespace.

    It is often wrongly assumed that xsl:strip-space removes excess whitespace such as the spacing used to align text in the illustrated comment element. It does not. The parser preserves significant whitespace mixed with non-whitespace text. To remove this extra spacing, use normalize-space, as in <xsl:value-of select="normalize-space(comment)"/>.

  3. Use translate to remove all whitespace.

    Another common mistake is assuming that normalize-space removes all whitespace. It only removes leading and trailing whitespace and collapses internal runs to single spaces. To remove all whitespace, use translate(irgendwas, '&#x20;&#xa;&#xd; &#x9;', '').

  4. Use an empty xsl:text element to prevent trailing stylesheet whitespace from being considered significant. xsl:text is normally used to preserve whitespace. However, a strategically placed empty xsl:text element can prevent trailing stylesheet whitespace from being interpreted as significant.

Compare the two modes in the document and stylesheet shown in the next two examples.

Example: Input.

<numbers>
  <number>10</number>
  <number>3.5</number>
  <number>4.44</number>
  <number>77.7777</number>
</numbers>

Example: Processing numbers with an empty xsl:text element and without an empty xsl:text element.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="numbers">
    Ohne leeres text-Element:
    <xsl:apply-templates mode="without"/>
    Mit leerem text-Element:
    <xsl:apply-templates mode="with"/>
  </xsl:template>
  <xsl:template match="number" mode="without">
    <xsl:value-of select="."/>,
  </xsl:template>
  <xsl:template match="number" mode="with">
    <xsl:value-of select="."/>,<xsl:text/>
  </xsl:template>
</xsl:stylesheet>

Example: Output.

Ohne leeres text-Element: 10, 3.5, 4.44, 77.7777,

Mit leerem text-Element: 10,3.5,4.44,77.7777,

Note that xsl:text has no special magic here. It works just as well if you replace <xsl:text/> with <xsl:if test="0"/>, although only do so if you enjoy confusing people. This inserts an element node between the comma and trailing newline, creating a whitespace-only node that is ignored. If you find that confusing, you can instead write <xsl:text>,</xsl:text> if you prefer.

Too little whitespace

  1. Use xsl:preserve-space to override xsl:strip-space for specific elements.

    There is little point using xsl:preserve-space unless you also use xsl:strip-space, because whitespace in the input and documents loaded with function document( ) is preserved by default.

    Warning!
    Remember that MSXML strips whitespace-only text nodes by default. Use xsl:preserve-space to counteract this problem.

  2. Use xsl:text to control output whitespace precisely.

    All whitespace inside an xsl:text element is preserved, allowing precise placement. Sometimes you can use xsl:text simply to insert line breaks:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="number">
    <xsl:value-of select="."/>
    <xsl:text>&#xa;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

Directly outputting newline characters is problematic because some platforms, such as Microsoft’s, expect carriage return plus newline. XML parsers must normalize this pair to a single newline, so no platform-independent stylesheet is possible here. Fortunately, most Windows editors and the command prompt handle single newlines correctly. The exception is Windows’ free Notepad editor.

  1. Use non-breaking spaces.

    XSLT does not treat character #xA0; (non-breaking space) as ordinary whitespace. In particular, both xsl:strip-space and normalize-space( ) ignore it. If you generally need to strip whitespace but preserve a few instances, try this character in the XML input. Non-breaking spaces are particularly useful in HTML output; elsewhere their usefulness depends on the renderer.

Discussion

These techniques handle whitespace, but it is also useful to understand their underlying XSLT rules.

The main rules apply to both stylesheets and input documents:

  1. A text node is never removed unless it contains only whitespace characters (#x20, #x9, #xD or #xA).

    Also understand the less common xml:space attributes in stylesheets and input documents.

  2. If an ancestor of a text node has an xml:space attribute set to preserve and no nearer ancestor sets attribute xml:space to default, whitespace-only text nodes are preserved.

    Stylesheet and source-document rules are considered separately. Stylesheet options are simple.

  3. The only stylesheet elements preserving whitespace-only nodes by default are xsl:text. Here, default means unless overridden with xml:space="preserve" as described in step 2 (see the next two examples).

Example: Stylesheet demonstrating xsl:text and xml:space="preserve".

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="numbers">
    Ohne xml:space="preserve":
    <xsl:apply-templates mode="without-preserve"/>
    Mit xml:space="preserve":
    <xsl:apply-templates mode="with-preserve"/>
  </xsl:template>
  <xsl:template match="number" mode="without-preserve">
    <xsl:value-of select="."/><xsl:text> </xsl:text>
  </xsl:template>
  <xsl:template match="number" mode="with-preserve" xml:space="preserve">
    <xsl:value-of select="."/><xsl:text> </xsl:text>
  </xsl:template>
</xsl:stylesheet>

Example: Output.

Ohne xml:space="preserve": 10 3.5 4.44 77.7777 Mit xml:space="preserve":
10

3.5

4.44

77.7777

The first version inserts only the single space inside the xsl:text element. In the second template xml:space="preserve" preserves all whitespace in the element, including two newlines (the first after <xsl:template ...> and the second after </xsl:text>).

Source-document rules are:

  • Initially, the list of elements preserving whitespace includes all elements in the document.

  • If an element matches a NameTest in an xsl:strip-space element, it is removed from the list of whitespace-preserving element names.

  • If an element name matches a NameTest in an xsl:preserve-space element, it is added to that list.

A NameTest is a simple name, such as doc, a namespace-prefixed name, such as my:doc, a wildcard, such as *, or a namespace-prefixed wildcard, such as my:*. In XSLT 2.0, *:doc is also permitted. Standard priority and import-precedence rules resolve conflicts between xml:strip-space and xml:preserve-space:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="http://www.ora.com/XSLTCookbook/ns/my">
  <!-- Whitespace in allen Elementen entfernen -->
  <xsl:strip-space elements="*"/>
  <!-- außer aus solchen im Namensraum "my" -->
  <xsl:preserve-space elements="my:*"/>
  <!-- und solchen namens foo -->
  <xsl:preserve-space elements="foo"/>
</xsl:stylesheet>

See also

One of the fullest accounts of whitespace handling appears in Michael Kay’s XSLT Programmer's Reference (Wrox, 2001), which also discusses import precedence in detail.

  

 

 

 

back to top