Java Reference
In-Depth Information
multiple threads running concurrently, and may be used multiple times in a given ses-
sion.
In addition to promoting thread safety,
Templates
instances can improve per-
formance because they represent compiled XSLT stylesheets.
The following example shows how you might perform a transformation without a
Templates
object:
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource ssStyleSheet = new StreamSource(new FileRead-
er("recipe.xsl"));
Transformer t = tf.newTransformer(ssStyleSheet);
t.transform(new
DOMSource(doc),
new
StreamRes-
ult(System.out));
You cannot access
t
's transformer from multiple threads. In contrast, the following
exampleshowsyouhowtoconstructatransformerfroma
Templates
objectsothat
it can be accessed from multiple threads:
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource ssStyleSheet = new StreamSource(new FileRead-
er("recipe.xsl"));
Templates te = tf.newTemplates(ssStylesheet);
Transformer t = te.newTransformer();
t.transform(new
DOMSource(doc),
new
StreamRes-
ult(System.out));
Thedifferencesarethecallto
Transformerfactory
's
Templates newTem-
plates(Source source)
method to create and return objects whose classes im-
plement the
Templates
interface, and the call to this interface's
Transformer
newTransformer()
method to obtain the
Transformer
instance.
Demonstrating the XSLT API
on
Listing 10-2
'
s movie XML document. Unfortunately, it's not possible to use the
DOM API to assign
ISO-8859-1
to the XML declaration's
encoding
attribute.
Also,it'snotpossibletouseDOMtooutputthistreetoafileorotherdestination.These
problems can be overcome by using XSLT, as demonstrated in the following example:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.METHOD, "xml");