1. strip-space_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6.   <product id="p3" price="1200" stock="19"/>
  7.   <product id="p4" price="1500" stock="5"/>
  8.   <product id="p5" price="1225" stock="3"/>
  9. </products>
  1. strip-space_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  4.   <xsl:strip-space elements="*"/>
  5.   <xsl:output indent="yes"/>
  6.   <xsl:template match="products">
  7.     <products>
  8.       <xsl:apply-templates/>
  9.     </products>
  10.   </xsl:template>
  11.   <xsl:template match="product">
  12.     <product no="{position()}" id="{@id}" price="{@price}" stock="{@stock}"/>
  13.   </xsl:template>
  14. </xsl:stylesheet>
  1. strip-space_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <products>
  4.   <product no="1" id="p1" price="3250" stock="4"/>
  5.   <product no="2" id="p2" price="1000" stock="5"/>
  6.   <product no="3" id="p3" price="1200" stock="19"/>
  7.   <product no="4" id="p4" price="1500" stock="5"/>
  8.   <product no="5" id="p5" price="1225" stock="3"/>
  9. </products>


If we remove xsl:strip-space, the values in the "no" attribute in output will change to: "2, 4, 6, 8, 10". Why? Because the "products" element contains whitespace only text nodes in the form of linefeeds. If we give xsl:apply-templates a select="*" or select="product", we don't need xsl:strip-space. When xsl:apply-templates doesn't have a select attribute it defaults to select="node()". On the child axis node() means: element(), comment(), processing-instruction() and text().

The "elements" attribute in xsl:strip-space takes a space separated list of element names as value. It is very common to use asteriks (*) meaning all elements. In our example we could have used "products" instead.

AltovaXML, the default XSLT processor in XMLSpy, has not implemented xsl:strip-space and xsl:preserve-space. In AltovaXML whitespace only text nodes are alwas stripped in advance. AltovaXML even strips whitespace only text nodes when they are important for input as is somethimes the case for mixed content. Some of Microsoft's processors and some other processors have stripping of whitespace only text nodes as an option that can be turned on or off. Only when turned off, the xsl:strip-space element is honored.

Updated 2009-03-19