XSLT: <xsl:strip-space> does not work

Solution 1:

It is not clear what you intend to get as an output, and what you expect from xsl:strip-whitespace in the first place. But one thing to note is that it doesn't strip all whitespace, but only that which is deemed insignificant under the "usual" rules. In particular, from XSLT 1.0 spec:

A text node is never stripped unless it contains only whitespace characters.

So, for example, this:

<foo>
  <bar>   </bar>
</foo>

will be stripped down to:

<foo><bar/></foo>

because it had 3 whitespace-only text nodes (after <foo> and before <bar>, between <bar> and </bar>, and after </bar> and before </foo>).

Note also that because you have <xsl:output indent="yes"> in your stylesheet, it will end up being transformed to:

<foo>
   <bar/>
<foo>

in the output.

On the other hand, this:

<foo>
   text1
   <bar>  text2  </bar>
   text3
</foo>

Will not be stripped at all, because all text nodes it contains are not purely whitespace nodes.

Solution 2:

Using the xslt from the original question, a <xsl:template match="text()"><xsl:value-of select="normalize-space(.)"/></xsl:template> should do the trick.

Solution 3:

Adding this as a second answer, because the explanation in the first one is still (hopefully) informative enough to keep it.

Assuming that by "trim" you mean "remove all whitespace immediately after opening and before closing tags", then the following additional template rules should do the trick:

<xsl:variable name="whitespace">&#x20;&#x9;&#xD;&#xA;</xsl:variable>

<!-- Trim all whitespace at beginning of string -->
<xsl:template name="trim-start">
   <xsl:param name="text"/>
   <xsl:variable name="first-char" select="substring($text, 1, 1)" />
   <xsl:choose>
     <xsl:when test="contains($whitespace, $first-char)">
       <xsl:call-template name="trim-start">
         <xsl:with-param name="text" select="substring($text, 2)" />
       </xsl:call-template>
     </xsl:when>
     <xsl:otherwise>
       <xsl:value-of select="$text" />
     </xsl:otherwise>
   </xsl:choose>
</xsl:template>

<!-- Trim all whitespace at end of string -->
<xsl:template name="trim-end">
   <xsl:param name="text"/>
   <xsl:variable name="last-char" select="substring($text, string-length($text), 1)" />
   <xsl:choose>
     <xsl:when test="contains($whitespace, $last-char)">
       <xsl:call-template name="trim-end">
         <xsl:with-param name="text" select="substring($text, 1, string-length($text) - 1)" />           </xsl:call-template>
       </xsl:call-template>
     </xsl:when>
     <xsl:otherwise>
       <xsl:value-of select="$text" />
     </xsl:otherwise>
   </xsl:choose>
</xsl:template>

<xsl:template match="text()">
  <xsl:call-template name="trim-start">
    <xsl:with-param name="text">
      <xsl:call-template name="trim-end">
        <xsl:with-param name="text" select=".">
      </xsl:call-template>
    <xsl:param>
  </xsl:call-template>
</xsl:template>