Wednesday 10 August 2011

Tricky whitespace handling in XSLT



Whitespace in a text string
             <description> This    is a test. </description>

normalize-space()
            normalize-space(description)
 translate() and replace()
            translate(description, '&#x20;&#x9;&#xD;&#xA;', ' ')
Whitespace-only text nodes
           <test>
                             <item/>
                        <item/>
             <item/>
</test>
Why strip whitespace-only text nodes
           <xsl:strip-space  elements="*"/>
xsl:strip-space and position()
           Input XML

<test>
  <item/>
  <item/>
  <item/>
</test>
XSLT stylesheet

<xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template  match="/">
    <test>
      <xsl:apply-templates/>
    </test>
  </xsl:template>
  <xsl:template  match="item">
    <no>
      <xsl:value-of  select="position()"/>
    </no>
  </xsl:template>
</xsl:stylesheet>
           
            Output XML

<test>
  <no>2</no>
  <no>4</no>
  <no>6</no>
</test>
xsl:strip-space and xsl:preserve-space
            <xsl:preserve-space elements="…"/>

Whitespace-only in mixed content
            <para>I <strong>love</strong> <name>Mozart</name></para>
<xsl:preserve-space  elements="resume headline para"/>
Whitespace in the XSLT stylesheet
            <xsl:value-of  select="firstname"/>
<xsl:text> </xsl:text>
<xsl:value-of  select="lastname"/>


<xsl:value-of  select="firstname"/>
<xsl:text> </xsl:text>
<xsl:value-of  select="lastname"/><xsl:for-each  select="item">
  <xsl:value-of  select="."/>,
</xsl:for-each>

<xsl:for-each  select="item">
<xsl:value-of  select="."/>, <xsl:text/>
</xsl:for-each>


<xsl:for-each  select="item">
  <xsl:value-of  select="."/>, <br/>
</xsl:for-each>

<xsl:for-each  select="item">  <xsl:value-of  select="."/>, <br/>&#160;</xsl:for-each>

No comments:

Post a Comment