9.3.2.3. Odds and ends
Before closing shop on JAXP, there are a few bits and pieces of TrAX
I haven't yet talked about. I won't treat these
completely, as they are less commonly used, but I will touch on them
briefly. First, TrAX introduces an interface called
SourceLocator, also in the
javax.xml.transform package. This class functions
for transformations exactly as the Locator class
did for SAX parsing: it supplies information about where action is
occurring. Most commonly used for error reporting, the interface
looks like this:
package javax.xml.transform;
public interface SourceLocator {
public int getColumnNumber( );
public int getLineNumber( );
public String getPublicId( );
public String getSystemId( );
}
I won't comment much on this interface, as it's pretty
self-explanatory. However, you should know that in the
javax.xml.transform.dom package, there is a
subinterface called DOMLocator. This interface
adds the getOriginatingNode( ) method, which
returns the DOM node being processed. This makes error handling quite
easy when working with a DOMSource, and is useful
in applications that work with DOM trees.
TrAX also provides a concrete class,
javax.xml.transform.OutputKeys, which defines
several constants for use in output properties for transformations.
These constants can then be used for setting properties on a
Transformer or a Templates
object. That leads me to the last subject dealing with TrAX.
The Templates interface in TrAX is used when a set
of output properties is desired across multiple transformations, or
when a set of transformation instructions can be used repeatedly. By
supplying a Source to a
TransformerFactory's newTemplates(
) method, you get an instance of the
Templates object:
// Get a factory
TransformerFactory factory = TransformerFactory.newInstance( );
// Get a Templates object
Templates template = factory.newTemplates(new StreamSource("html.xsl"));
At this point, the template object would be a
compiled representation of the transformation detailed in html.xsl (in this example, a stylesheet that
converts XML to HTML). By using a Templates
object, transformations can be performed from this template across
threads, and you also get some optimizations, because instructions
are precompiled. Once you have gone that far, you need to generate a
Transformer, but from the
Templates object, rather than the factory:
// Get a transformer
Transformer transformer = template.newTransformer( );
// Transform
transformer.transform(new DOMSource(orderForm),
new StreamResult(res.getOutputStream( )));