web analytics
Whitespace Handling in XSL Transformation Options
Posted: Tuesday, September 12, 2017 10:40:17 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 1005
Points: 4242

In XML, carriage return, linefeed, tab, and the spacebar are the whitespace characters. By default, XSLT preserves whitespaces. White-space in the stylesheet is ignored as long as it occurs between XML elements only. For example, the following XSL template:

<xsl:template match="foo">

will produce the following results from the processor's point of view.


To avoid the unwanted whitespaces, you should try the following XSL template

<xsl:template match="foo">

Also you are applying the following template

<xsl:apply-templates />

It applies to "white-space-only" nodes as well  because the default XSLT rule for text nodes says "copy them to the output". For instance:

  <data> value </data>

contains three text nodes:

  1. "\n··" (right after <xml>)
  2. "·value·"
  3. "\n" (right before </xml>)

To avoid that #1 and #3 sneak into the output (which is the most common reason for unwanted spaces), you can override the default rule for text nodes by declaring an empty template:

<xsl:template match="text()" />

All text nodes are now muted and text output must be created explicitly:

<xsl:value-of select="data" />

To remove white-space from a value, you could use the normalize-space() XSLT function:

<xsl:value-of select="normalize-space(data)" />

But careful, since the function normalizes any white-space found in the string, e.g. "·value··1·" would become "value·1".

Additionally you can use the <xsl:strip-space> and <xsl:preserve-space> elements. By default, XSLT templates have <xsl:preserve-space> set, which will keep whitespace in your output. You can add <xsl:strip-space elements="*"> to tell it to where to delete whitespace.

Posted: Tuesday, September 12, 2017 10:40:17 AM
Users browsing this topic

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

© 2019 Digcode.com. All rights reserved.