I had a similar situation where I needed to generate a text file from the data inside an XML document. The solution implemented used XSLT to perform the transformation from XML to a CSV. This is returned as a String object which can be written to a file. You can also modify the method below to output directly to a file.
Here are the pieces:
XSLT snippets:
<xsl

utput method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:for-each select="LineList/Lines">
<xsl:apply-templates select="*"/>
</xsl:for-each>
</xsl:template>
<xsl:template match="*">
<xsl:choose>
<!-- No comma on the last element -->
<xsl:when test="position()=last()"><xsl:value-of select="."/></xsl:call-template></xsl:when>
<!-- Comma required. Not the last element -->
<xsl

therwise><xsl:value-of select="."/>,</xsl

therwise>
</xsl:choose>
</xsl:template>
Java Snippet:
// Method to convert an XML document object to an String
private static String transformXMLToString( String styleSheet, Document orig ) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Transformer transformer = factory.newTransformer( new StreamSource( styleSheet ) );
StreamResult result = new StreamResult( baos );
transformer.transform(new DOMSource( orig ), result);
}catch(TransformerConfigurationException e ){
System.out.println("TransformerConfigurationException: " + e.getMessage() );
}catch(TransformerException e){
System.out.println("TransformerException: " + e.getMessage() );
}
return baos.toString();
}
Pass the XSL stylesheet and the document containing the XML object to the method and a String will be returned which contains the CSV. Note: The above snippets are untested as I had to modify them for presentation in the forums. The ideas are sound and should work for you. The neat part is this is fast and reusable with different stylesheets. For example, let's say you only wanted the first 10 elements in the XML document. You can design a new stylesheet and reuse the existing method.
Hope this helps.
Glen Jansen
Java/XML Cert in Training.