[thelist] Can't seem to use XSLT with SAX in Java 1.5

Roger Ly evolt at matchpenalty.com
Wed Sep 28 14:18:51 CDT 2005


Hey all,

I am playing around with the XML processing abilities that came standard
with Java 1.4 and 1.5.  Included with it is the ability to use SAX XML
handling, and supposedly, the ability to apply XSL transformations on a file
processed with SAX.

Unfortunately, I can't seem to get any XSLT to work properly using SAX.

The following is a snippet of code, that uses the ordinary XSL transforms
with javax.xml.transform and XSL transforms with javax.xml.transform.sax.
The first one does what I expect, while the second doesn't even come close:

code
====
public void doSomething()
{
       System.out.println("\n**************** regular transform
************************");
       // transformer from XSL file
	Transformer trans =
TransformerFactory.newInstance().newTransformer(new StreamSource(new
File("output.xsl")));
	// apply transformation on XML file and pipe to stdout
	trans.transform(new StreamSource(new File("output.xml")), new
StreamResult(System.out));
			
	System.out.println("\n**************** SAX transform
************************");
	// transformer from XSL file
	TransformerHandler saxTransHandler =
((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerH
andler(new StreamSource(new File("output.xsl")));
	// pipe to stdout
	saxTransHandler.setResult(new StreamResult(System.out));
	// new SAX parser
	SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
	// set content handler on the XML reader of the parser
	XMLReader reader = saxParser.getXMLReader();
	reader.setContentHandler(saxTransHandler);
	// parse XML file on disk and apply transform via content handler
	reader.parse(new InputSource(new FileReader(new
File("output.xml"))));
}

output.xml
========
<?xml version="1.0" encoding="us-ascii" ?>
<foo>
	<bar>hello</bar>
	<bar2>hello</bar2>
</foo>

output.xsl
========
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" />

<xsl:template match="foo">
	<myoutput>
		<xsl:apply-templates select="bar" />
	</myoutput>
</xsl:template>

<xsl:template match="bar">
	<mybar>
		<xsl:value-of select="." />
	</mybar>
</xsl:template>

</xsl:stylesheet>



stdout
=====
**************** regular transform ************************
<?xml version="1.0"
encoding="UTF-8"?><myoutput><mybar>hello</mybar></myoutput>
**************** SAX transform ************************
<?xml version="1.0" encoding="UTF-8"?>
	hello
	hello


Any thoughts why this isn't working properly?  I need to use SAX because of
a third-party library which only implements a SAX parser as input to my XSL.
I could just dump the output of the SAX parser to a temporary file or DOM
object, and use that, but I would like to avoid that step if at all
possible.

Thanks,

Roger




More information about the thelist mailing list