Most Java applications I work on save their data in XML. One of the reasons I like XML is that it is easy to post-process the files with XSLT. For example, I often save raw data in XML and use a style sheet or two to generate reports in HTML, PDF, or SVG.
I used to ship a separate application to post-process the files but increasingly users are demanding an integrated solution that emulates the "Export..." or "Save As..." menu commands familiar from their commercial productivity applications.
The search for a good solution eventually led me to SAXTransformerFactory. For the remainder of this discussion, I assume you have notions of SAX parsing, TrAX (the standard Java API for XSLT processors), and XSLT. If you need some background, see Resources for referrals.
As you know, SAX parsing requires you to write a ContentHandler that processes parser events. SAXTransformerFactory essentially turns the XSLT processor into a ContentHandler.
Why bother, you may ask? After all, TrAX also supports SAXSource to interface with SAX parsers. Indeed, if you use a full-blown SAX parser, SAXTransformerFactory is seldom useful. But I have found that it pays to generate those events from my application, without a parser.
Consider Figure 1. Two things happen: First the application writes data in an XML file and then the XSLT processor, which is another application, styles the data in HTML.
Figure 1. Typical XML and XSLT application
What happens if you integrate the XSLT processor in the application? You must still feed it an XML document. Most applications use a temporary file or a String for that purpose. I believe that ContentHandler is more attractive.
Indeed, in the first case, the application writes the XML document, which the XSLT processor immediately parses (often
through a SAX parser). Wouldn't it be more efficient if, as Figure 2 illustrates, the application would issue the SAX events itself? In Figure 2, instead of writing to a file, the application calls the processor's ContentHandler directly, effectively simulating the parser.
The second model is more efficient, it uses less memory, and saves you from the headache of creating and deleting temporary files.
Figure 2. The application simulates the parser
Furthermore it turns out that it's easy to simulate the parser. The application most likely has functions to write start tags, end tags, and escape characters already. It suffices to replace them with their SAX equivalent, respectively to startElement(), endElement(), and characters(). In other words, code such as writer.write("<ps:key>") becomes
contentHandler.startElement ("http://www.psol.com/2001/08/dw/tip","key","ps:key",attributes). It might be longer but it's not much tougher to write.
The asXML() method writes a Properties object as XML, but it does not write to a file; it uses a ContentHandler instead.
The code is straightforward but for namespaces. Experience shows it is safer to issue startPrefixMapping() and pass the xmlns declaration as a regular attribute as well.
Listing 1. asXML() simulates the SAX parser
protected static void asXML(Properties properties,ContentHandler contentHandler)
throws SAXException
{
AttributesImpl attributes = new AttributesImpl();
contentHandler.startDocument();
contentHandler.startPrefixMapping("ps",
"http://www.psol.com/2001/08/dw/tip");
attributes.addAttribute("","ps","xmlns:ps","CDATA",
"http://www.psol.com/2001/08/dw/tip");
contentHandler.startElement("http://www.psol.com/2001/08/dw/tip",
"properties","ps:properties",attributes);
attributes.clear();
Enumeration enumeration = properties.propertyNames();
while(enumeration.hasMoreElements())
{
String name = (String)enumeration.nextElement(),
value = properties.getProperty(name);
contentHandler.startElement("http://www.psol.com/2001/08/dw/tip",
"property","ps:property",new AttributesImpl());
contentHandler.startElement("http://www.psol.com/2001/08/dw/tip",
"key","ps:key",attributes);
contentHandler.characters(name.toCharArray(),0,name.length());
contentHandler.endElement("http://www.psol.com/2001/08/dw/tip",
"key","ps:key");
contentHandler.startElement("http://www.psol.com/2001/08/dw/tip",
"value","ps:value",attributes);
contentHandler.characters(value.toCharArray(),0,value.length());
contentHandler.endElement("http://www.psol.com/2001/08/dw/tip",
"value","ps:value");
contentHandler.endElement("http://www.psol.com/2001/08/dw/tip",
"property","ps:property");
}
contentHandler.endElement("http://www.psol.com/2001/08/dw/tip",
"properties","ps:properties");
contentHandler.endPrefixMapping("ps");
contentHandler.endDocument();
} |
To apply a style sheet on the result of asXML(), use the code in Listing 2. First, like regular TrAX, create a TransformerFactory. Next make sure it is compatible with SAXTransformerFactory by calling getFeature() and, if successful, typecast it as TransformerFactory.
Finally use newTransformerHandler() to request a TransformerHandler object. The method takes a URI to the style sheet as parameter. TransformerHandler implements ContentHandler and can be given as a parameter to asXML().
If you are familiar with TrAX, you might wonder where to call transform(). The answer is you don't. TransformerHandler applies the style sheet as it is being fed SAX events.
TransformerHandler is the regular XSLT processor; it places no restrictions on the
style sheet, such as table.xsl in Listing 3.
Listing 3. table.xsl
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ps="http://www.psol.com/2001/08/dw/tip"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Properties</title>
</head>
<body>
<table>
<tr><td>Key</td><td>Value</td></tr>
<xsl:for-each select="ps:properties/ps:property">
<tr>
<td><xsl:value-of select="ps:key"/></td>
<td><xsl:value-of select="ps:value"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet> |
What happens if you don't want HTML but prefer the raw XML document? The easiest solution is to provide one extra style sheet that does not modify the input, such as identity.xsl in Listing 4.
Listing 4. identity.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet> |
If you're concerned about performance, you might prefer to use a serializer. A serializer is a ContentHandler that writes its input in an XML document. If Xalan is your XSLT processor, turn to org.apache.xalan.serialize.Serializer. Since it's a ContentHandler, it works directly with asXML(), as shown in Listing 5.
Other applications of SAXTransformerFactory
SAXTransformerFactory is also useful whenever you process XML documents through several stages. For example, I recently implemented it in a so-called "pipe" that transforms input documents through a combination of XSLT style sheets and custom-made filters.
-
Xalan is an open-source XSLT processor that supports
SAXTransformerFactory -
SAX, the power API, a chapter excerpted from the author's book, XML by Example, second edition, due out from Que Publishing in September 2001, covers SAX in detail.
-
Sun's Java API for XML Parsing, Version 1.1 by Brett McLaughlin, introduces JAXP 1.1 which combines SAX, TrAX and DOM. Turn to Java Technology and XML for the official page with Sun.
-
Transforming DocBook documents using XSLT by David Mertz is a good starting point to learn XSLT.
-
Saxon: Anatomy of an XSLT processor by Michael Kay is a most interesting discussion on XSLT processors.
-
IBM FAQs answer frequently asked questions about XML and IBM products.
- Find out how you can become an IBM Certified Developer in XML and related technologies.

Benoît Marchal is a consultant and writer based in Namur, Belgium. He is the author of
XML by Example
,
Applied XML Solutions
and
XML
and the Enterprise. He is a columnist for Gamelan. Details on his latest projects are at marchal.com. You can contact Benoît at bmarchal@pineapplesoft.com.
The author offers "special thanks to Frédéric George for introducing me to SAXTransformerFactory."




