My thoughts as an enterprise Java developer.

Monday, June 16, 2008

XSL: Preserving line feeds, tabs, and spaces in data while still wrapping text

I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve (so I couldn't use

) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use

).

After some research and help from a co-worker (Patricia Eromosele) I made the XSL template below that achieves that. An example of how to call it follows:


<p>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="text"/>
</xsl:call-template>
</p>



<xsl:template name="prewrap">
<xsl:param name="text" select="."/>
<xsl:variable name="spaceIndex" select="string-length(substring-before($text, ' '))"/>
<xsl:variable name="tabIndex" select="string-length(substring-before($text, '&#x09;'))"/>
<xsl:variable name="lineFeedIndex" select="string-length(substring-before($text, '&#xA;'))"/>
<xsl:choose>
<xsl:when test="$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0"><!-- no special characters left -->
<xsl:value-of select="$text"/>
</xsl:when>
<xsl:when test="$spaceIndex > $tabIndex and $lineFeedIndex > $tabIndex"><!-- tab -->
<xsl:value-of select="substring-before($text, '&#x09;')"/>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'&#x09;')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$spaceIndex > $lineFeedIndex and $tabIndex > $lineFeedIndex"><!-- line feed -->
<xsl:value-of select="substring-before($text, '&#xA;')"/>
<br/>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,'&#xA;')"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$lineFeedIndex > $spaceIndex and $tabIndex > $spaceIndex"><!-- two spaces -->
<xsl:value-of select="substring-before($text, ' ')"/>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text>
<xsl:call-template name="prewrap">
<xsl:with-param name="text" select="substring-after($text,' ')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><!-- should never happen -->
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

Tip: Java thread dumps on linux

To get a thread dump in Java on linux run "pkill -3 java"

Ethical programming

It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter.
-- Nathaniel Borenstein
(Passed on by Reid Nimz.)