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
Use
xsl:strip-spaceto 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 illustratedcommentelement 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 andxsl:preserve-spaceto override this for specific elements (see below). In XSLT 2.0 you can useelements="*:Name"to strip whitespace from all elements with that local name, regardless of namespace.Use
normalize-spaceto remove excess whitespace.It is often wrongly assumed that
xsl:strip-spaceremoves excess whitespace such as the spacing used to align text in the illustratedcommentelement. It does not. The parser preserves significant whitespace mixed with non-whitespace text. To remove this extra spacing, usenormalize-space, as in<xsl:value-of select="normalize-space(comment)"/>.Use
translateto remove all whitespace.Another common mistake is assuming that
normalize-spaceremoves all whitespace. It only removes leading and trailing whitespace and collapses internal runs to single spaces. To remove all whitespace, usetranslate(irgendwas, ' 

 	', '').Use an empty
xsl:textelement to prevent trailing stylesheet whitespace from being considered significant.xsl:textis normally used to preserve whitespace. However, a strategically placed emptyxsl:textelement 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
Use
xsl:preserve-spaceto overridexsl:strip-spacefor specific elements.There is little point using
xsl:preserve-spaceunless you also usexsl:strip-space, because whitespace in the input and documents loaded with functiondocument( )is preserved by default.Warning!
Remember that MSXML strips whitespace-only text nodes by default. Usexsl:preserve-spaceto counteract this problem.Use
xsl:textto control output whitespace precisely.All whitespace inside an
xsl:textelement is preserved, allowing precise placement. Sometimes you can usexsl:textsimply 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>
</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.
Use non-breaking spaces.
XSLT does not treat character
#xA0;(non-breaking space) as ordinary whitespace. In particular, bothxsl:strip-spaceandnormalize-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:
A text node is never removed unless it contains only whitespace characters (#x20, #x9, #xD or #xA).
Also understand the less common
xml:spaceattributes in stylesheets and input documents.If an ancestor of a text node has an
xml:spaceattribute set topreserveand no nearer ancestor sets attributexml:spacetodefault, whitespace-only text nodes are preserved.Stylesheet and source-document rules are considered separately. Stylesheet options are simple.
The only stylesheet elements preserving whitespace-only nodes by default are
xsl:text. Here, default means unless overridden withxml: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
NameTestin anxsl:strip-spaceelement, it is removed from the list of whitespace-preserving element names.If an element name matches a
NameTestin anxsl:preserve-spaceelement, 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.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de