XML Transformations in Java

The final crucial component of the Java API For XML Processing (JAXP) is the ability to programmatically transform XML documents via XSLT. Details of XSLT transformations are covered in detail in Chapter 9, “Transforming XML Data into Other Formats with XSLT.” This section focuses on methods for using Java to produce these XSLT transformations.

The reference implementation for the JAXP transformation engine is the Apache Xerces Xalan XSLT engine, and it is the transformation engine that will be used for the example in this section. The Apache Xalan XSLT engine source code is made available under the open source Apache License and is contained in the Java XML Pack that is available for downloading at http://xml.apache.org/xalan-j/index.html.

The JAXP specification provides an extremely straightforward method for doing XSLT transformations in Java. As an example, we will build a small application that transforms the XML file example from the beginning of this chapter into HTML. The XSLT file that will be used for this example is shown in Listing 16.7. This XSLT transformer takes our example XML file and turns it into an HTML file that prints out all the standards listed in the document.

As with all the other Java API for XML interfaces, the XSLT transformation engine isn't instantiated directly, but is instead generated via a factory—in this case a TransformerFactory that queries the system for the available transformers and generates one on demand:

TransformerFactory transformerFactory =  TransformerFactory.newInstance(); 

Now that a TransformerFactory has been created, it is necessary to prepare the data sources that will be transformed. Because files will be used in this example, Java IO File Objects are created for the XML and XSLT file examples:

File xmlFile = new File("example.xml"); 
File xsltFile = new File("example.xslt");

The Java Transformation API cannot use raw Java File objects for transformation. Instead, it defines a custom interface called Source to which all XML data sources must conform. Luckily, a wrapper object called StreamSource is provided that will convert Java IO file objects into StreamSource objects that implement the Source interface.

Source xmlSource =  new StreamSource(xmlFile); 
Source xsltSource =   new StreamSource(xsltFile);

Now that the source objects have been created, we need to specify a location for the transformed XML data to be placed into. This can be another file, a network communications pipe, or—as is the case here—a standard PrintStream like the System Console. A StreamResult object is created from the desired output stream similar to how StreamSource objects were created for the input stream:

StreamResult streamResult = new StreamResult(System.out); 

Now the Transformation engine object must be created. The Transformation engine object is created from the TransformerFactory object created earlier, and it is created via the newTransformer method. When the Transformer object is created, the XSLT Source object is passed in as part of the call to the newTransformer. This creates a Transformer tied to that specific XSLT Stylesheet and can be used over and over again to transform multiple documents with the style sheet. (The methods available to the Transformer object are shown in Table 16.4.)

Transformer transformer = transformerFactory.newTransformer(xsltSource); 

Table 16.4. Transformer Methods
clearParameters Clears all the XSLT parameters that have been set.
getErrorListener Returns the error handler for this transformation.
getOutputProperties Returns the output properties for this transformation.
getOutputProperty Returns a single output property for this transformation.
getParameter Returns an XSLT parameter that has been set.
getURIResolver Returns the handler used to resolve URIs.
setErrorListener Sets the error handler for the transformation.
setOutputProperties Sets the output properties for this transformation.
setOutputProperty Sets a single output property for this transformation.
setParameter Sets an XSLT parameter for this transformation.
setURIResolver Sets the handler used to resolve URIs.
transform Transforms the specified XML document using the specified XSLT and outputs the results.

We're now ready to run the XSLT transformation. The Transformer object contains a method called transform that actually runs the transformation. This method takes two arguments. The first is the StreamSource to be used to fetch the XML document to be transformed, which in our case is the xmlSource object corresponding to the sample XML file. The second is the StreamResult object to send the transformed document to, which in this case is the streamResult object corresponding to the System Console.

transformer.transform(xmlSource, streamResult); 

That's it. The full implementation of code for this example is contained in Listing 16.6. The HTML output generated by the transformation example is shown in Listing 16.5, and finally the output displayed in a Web browser is contained in Figure 16.2.

Figure 16.2. Browser displaying the output from the Transformer example.


Listing 16.5. HTML Output from the Transformer Example
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example Transformation</title>
</head>
<body>
<center>
<h1>Example Transformation</h1>
</center>
<h1>Standard</h1>
<h2>Java API for XML Processing(JAXP)</h2>
<h1>Standard</h1>
<h2>Document Object Model(DOM)</h2>
<h1>Standard</h1>
<h2>Simple API for XML(SAX)</h2>
<h1>Parser</h1>
<h2>Xerces</h2>
<h1>Parser</h1>
<h2>Crimson</h2>
<h1>Parser</h1>
<h2>GNUJAXP</h2>
</body>
</html>

Listing 16.6. Java XSLT Transformer Code Example
import java.io.File;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
public class SimpleTransform
{
  public static void main(String[] args) throws TransformerException
  {
    // Generate a Transformer Factory that will allow Transformers to be
    // generated
    TransformerFactory transformerFactory =  TransformerFactory.newInstance();
    // Create Java File object to load the example xml file from
    File xmlFile = new File("example.xml");
    // Create Java File object to load the example xslt file from
    File xsltFile = new File("example.xslt");
    // Create StreamSource object for the example xml file
    Source xmlSource =  new StreamSource(xmlFile);
    // Create StreamSource object for the example xslt file
    Source xsltSource =   new StreamSource(xsltFile);
    // Create the StreamResult object to inform the transformer where to send
    // the transformed document
    StreamResult streamResult = new StreamResult(System.out);
    // Create the transformer for this XSLT document from the generated
    // TransformerFactory object,
    Transformer transformer = transformerFactory.newTransformer(xsltSource);
    // Finally, run the XSLT transformation against the StreamSource generated
    // from sample XML file passing the results to the specified StreamResult,
    // which in this case is the Console
    transformer.transform(xmlSource, streamResult);
  }
}

Listing 16.7. Sample XSLT File
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
  <head>
    <title>Example Transformation</title>
  </head>
  <body>
    <center>
      <h1>Example Transformation</h1>
    </center>
<xsl:apply-templates/>
   </body>
</html>
</xsl:template>

<xsl:template match="standard">
  <h1>Standard</h1>
  <h2><xsl:value-of select="."/></h2>
</xsl:template>

<xsl:template match="parser">
  <h1>Parser</h1>
  <h2><xsl:value-of select="."/></h2>
</xsl:template>

</xsl:stylesheet>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.44.199