David Jaquay
David Jaquay

Reputation: 1062

javax.xml.transform.Transformer is removing needed whitespace (xml to text transformation)

I'm trying to convert XML to text, using javax.xml.transform. xsltproc will correctly transform my XML to properly formatted text, while the following code produces output with almost all whitespace removed:

final ByteArrayOutputStream out = new ByteArrayOutputStream();

final InputStream  is          = getClass().getResourceAsStream( xslResourceName );
final StreamSource xsltSrc     = new StreamSource( is );
final Transformer  transformer = tFactory.newTransformer( xsltSrc );
final Source       src         = new StreamSource( new StringReader( xmlData ) );
final Result       res         = new StreamResult( out );

transformer.setOutputProperty( "method", "text" );
transformer.setOutputProperty( "omit-xml-declaration", "yes" );
transformer.transform( src, res );

return out.toString();

The spaces are intentionally being added by the XSLT, using tags such as:

<xsl:value-of select="substring(concat(concat($frontpadding,$cellvalue),$blank),1,$width)"/>

For a larger example, the source xml might have:

<reportheader display="true">
  <name>Hours01</name>
  <date>2011-04-14</date>
  <description>Hours Report</description>
  <pagewidth>130</pagewidth>
</reportheader>

The xsl has:

<xsl:template match="reportheader">
<xsl:if test="@display='true'">
    <xsl:variable name="col1width" select="12"/>
    <xsl:variable name="datewidth" select="10"/>
    <xsl:variable name="col2width" select="$pagewidth - $col1width - $datewidth"/>
    <xsl:copy-of select="substring(concat(name,$blank),1,$col1width)"/>
    <xsl:copy-of select="substring(concat(description,$blank),1,$col2width)"/>
    <xsl:copy-of select="substring(concat(date,$blank),1,$datewidth)"/> 
    <xsl:text>&#xa;</xsl:text>
    <xsl:text>&#xa;</xsl:text>
</xsl:if>
</xsl:template>

The xsltproc output is:

Hours01     Hours Report                                                                                                2011-04-14

And the javax.xml.transformer.Transformer output is:

Hours01Hours Report2011-04-14

Upvotes: 1

Views: 2016

Answers (2)

Shiva
Shiva

Reputation: 11

Try the xml character for space in your xslt.

&#160;

Or use text tag..

<xsl:text> </xsl:text>

I hope this helps.

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86744

How did you define $blank? When I do

<xsl:variable name="blank">                                  </xsl:variable>

I get the same results as you. However, the following produced the results you desire

<xsl:variable name="blank" select="'                                                '"/>

Upvotes: 1

Related Questions