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>
</xsl:text>
<xsl:text>
</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
How did you define $blank? When I do
I get the same results as you. However, the following produced the results you desire