xsl:preserve-space

  1. preserve-space_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <description><strong>Only</strong> <em>Sommer Sales</em>.</description>
  5.   <product id="p1" price="3250" stock="4"/>
  6.   <product id="p2" price="1000" stock="5"/>
  7.   <product id="p3" price="1200" stock="19"/>
  8.   <product id="p4" price="1500" stock="5"/>
  9.   <product id="p5" price="1225" stock="3"/>
  10. </products>
  1. preserve-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:preserve-space elements="description"/>
  6.   <xsl:output indent="no"/>
  7.   <xsl:template match="products">
  8.     <products>
  9.       <xsl:apply-templates/>
  10.     </products>
  11.   </xsl:template>
  12.   <xsl:template match="description|strong|em">
  13.     <xsl:copy>
  14.       <xsl:apply-templates/>
  15.     </xsl:copy>
  16.   </xsl:template>
  17.   <xsl:template match="product">
  18.     <product no="{position()}" id="{@id}" price="{@price}" stock="{@stock}"/>
  19.   </xsl:template>
  20. </xsl:stylesheet>
  1. preserve-space_1-output.xml

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

Comment

We need to use <xsl:preserve-space elements="description"/> to preserve the whitespace only text node between <strong>Only</strong> and <em>Sommer Sales</em>. Note that AltovaXML in XMLSpy has not implemented xsl:strip-space and xsl:preserve-space. AltovaXML is always stripping whitespace only text nodes, even when they are important as in this example!

In this example indention of output has been turned off to make it easier to see the whitespace only text nodes in mixed content.

Updated 2009-03-19