Text nodes in XSLT

It's amazing how many people have issues with whitespace handling in XSLT. I admit it's counter intuitive unless you start thinking in XML terms (remember: XSLT stylesheet is first parsed by an XML parser). The rule I'll explain today is very simple: whitespace-only text nodes from XSLT stylesheet are not copied to the output.

In the example mentioned by Alexandar …
<input type="submit">
  <xsl:attribute name="value">
    Login
  </xsl:attribute>
</input>
… a single text node within the xsl:attribute element (as parsed by XML parser) includes the Login text as well as a few whitespace characters. To get rid of the extra whitespace characters (it looks like the target application hates having leading whitespaces in submit button names), you could write the whole value in-line (now there is no extra whitespace in the attribute value):
<xsl:attribute name="value">Login</xsl:attribute>
Alternatively, you could split the contents of the xsl:attribute element into whitespace-only text nodes (which are not copied to the output) and a non-whitespace text node (containing the Login text). The easiest way to do it is to insert an xsl:text element within the xsl:attribute element:
<xsl:attribute name="value">
  <xsl:text>Login</xsl:text>
</xsl:attribute>

This post is part of You've asked for it series of articles.

2 comments:

Juno said...

Or, you can also do like this.
<xsl:attribute name="value" select="'Login'>

Anonymous said...

I like that last paragraph,
you could split the contents of the xsl:attribute element into whitespace-only text nodes (which are not copied to the output) and a non-whitespace text node (containing the Login text). The easiest way to do it is to insert an xsl:text element within the xsl:attribute element:

-short and sweat

Post a Comment