Browse DevX
Sign up for e-mail newsletters from DevX


Programmatically Apply XSLT in a Dynamic Java Application-3 : Page 3




Building the Right Environment to Support AI, Machine Learning and Deep Learning

JAXP Transformations
JAXP provides an abstract framework for parsing XML documents, and it is independent of a specific parser implementation. Rather than directly instantiating processing and transformation objects, JAXP employs a factory design pattern and provides static methods that return instances of the appropriate type.

Through the factory class, you can specify the properties of the object that will be returned and query an object of that type to see which properties have been set. The abstraction layer outlined by the JAXP specification essentially defines a pluggability layer. This layer allows any JAXP-compliant parser to be "plugged-in" at runtime to fulfill the parsing commands sent from the application component via the JAXP API.

The JAXP transformation API (previously know as the TRaX API) can be used for transforming XML programmatically via SAX or DOM or declaratively by applying an XSLT stylesheet. The transformation API is primarily contained within two packages: javax.xml.transform and javax.xml.transform.stream.

To apply an XSLT stylesheet to an XML document via JAXP, begin by obtaining an instance of a TransformerFactory object from its corresponding factory (yes, you'll obtain a factory from a factory):

try {
    TransformerFactory  tFactory =

The next step is to create a Transformer object. Use the XSL source file as an argument to pass into the TransformerFactory's static newTransformer() factory method:

Source xslSource = new 
StreamSource( "test.xsl" ); Transformer transformer =
tFactory.newTransformer( xslSource );

Now you have a Transformer object that has adopted the XSL templates as a natural part of its transformation process. You can now perform the transformation by invoking the Transformer class's transform() method.

You must supply two arguments to the transform() method. The first must be of type javax.xml.transform.Source. Any object whose class implements the Source interface can be used as the source for a JAXP transformation. The second argument must be of type javax.xml.transform.Result. Any object whose class implements the Result interface can be used as the result for a JAXP transformation.

The following code will perform a transformation using the Transformer object created earlier (which has been set with the template transformations specified in the test.xsl stylesheet):

    transformer.transform( new 
StreamSource( "test.xml" ), new StreamResult( new
FileOutputStream( "test_output.txt" ) ); } catch( Exception ex )
{ ex.printStackTrace(); }

The transformation will be applied using the test.xml file as the XML input tree, and the resulting output will be sent to a file named test_output.txt.

Thanks for your registration, follow us on our social networks to keep up-to-date