Transforming XML with XSLT
We saw the use of the javax.xml.transform
package and two of its subpackages in the output( )
method of Example 19-2. There it was used to
perform an “identity transform,” converting a DOM tree into the
corresponding XML file. But transforming the format of an XML document
is not the only purpose of these packages. They can also be used to
transform XML content according to the rules of an XSL stylesheet. The
code required to do this is remarkably simple; it’s shown in Example 19-3. This example uses
javax.xml.transform.stream
to read
files containing a source document and a stylesheet, and to write the
output document to another file. JAXP can be even more flexible,
however: the transform.dom
and
transform.sax
subpackages allow the
program to be rewritten to (for example) transform a document
represented by a series of SAX parser events into a DOM tree, using a
stylesheet read from a file.
Example 19-3. XSLTransform.java
package je3.xml; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; /** * Transforms an input document to an output document using an XSLT stylesheet. * Usage: java XSLTransform input stylesheet output **/ public class XSLTransform { public static void main(String[ ] args) throws TransformerException { // Set up streams for input, stylesheet, and output. // These do not have to come from or go to files. We can also use the // javax.xml.transform. {dom,sax} packages use DOM trees and streams of // SAX ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.