XML technologies / XSLT / Java and XSLT / XSLT processing with Java / A simple example

(Excerpt from “Java und XSLT” by Eric M. Burke)

Let us begin with perhaps the simplest possible program: a Java application transforming a static XML file into HTML using an XSLT stylesheet. Starting simply helps isolate problems in your development environment, particularly CLASSPATH problems, before tackling more complex tasks.

We will write two versions, one for Xalan and another for SAXON. A subsequent implementation using JAXP will show how the same code can support different processors.

CLASSPATH problems

CLASSPATH problems often explain failing code, especially with XML APIs. Since many tools use XML, your system may contain several implementations of DOM and SAX. Before trying this chapter’s examples, ensure your CLASSPATH contains no older parsers.

Subtler problems arise when an older library exists in Java 2’s optional packages directory. Every JAR found in jre/lib/ext is automatically available to the JVM without adding it to CLASSPATH. Look for files such as jaxp.jar and parser.jar that might contain older incompatible XML APIs. If problems occur, remove all JAR files from the optional packages directory.

Unfortunately, identifying where JAR files came from requires detective work. Java 2 version 1.3 introduced improved JAR features such as version information, but most JARs you encounter will probably not provide them.

Design

The application is simple. A single class contains a main( ) method performing the transformation. Two arguments specify the XML filename followed by the XSLT filename. Results are simply sent to System.out. We use these XML data:

<?xml version="1.0" encoding="ISO-8859-1"?>
<meldung>Jawohl, es hat geklappt!</meldung>

The following stylesheet sets its output method to text and outputs only the content of element <meldung>, here the text Jawohl, es hat geklappt!.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="ISO-8859-1"/>
    <!-- die Meldung wird einfach in den Ergebnisbaum kopiert -->
    <xsl:template match="/">
        <xsl:value-of select="meldung"/>
    </xsl:template>
</xsl:stylesheet>

Because filenames are command-line arguments, other XML and XSLT files work too. You might try one of the federal president examples from previous pages.

Xalan 1 implementation

The next example contains the complete Xalan implementation. As the comments indicate, it was developed and tested with Xalan 1.2.2, Apache’s current XSLT processor. Xalan-specific code uses fully qualified class names such as org.apache.xalan.xslt.XSLTProcessor.

Note:
No Xalan 2 example is shown because it supports Sun’s JAXP. The JAXP version runs with Xalan 2 just like any other JAXP-compatible processor.

Example: BeispielXalan1.java

package kapitel5;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import org.xml.sax.SAXException;


/**
* Ein einfaches Beispiel für Xalan 1. Der Code wurde im Original mit
* Xalan 1.2.2 geschrieben und funktioniert nicht mit Xalan 2.
*/
public class BeispielXalan1 {
  
  /**
   * Nimmt zwei Kommandozeilenparameter an: den Namen einer XML-Datei und
   * den Namen eines XSLT-Stylesheets. Das Ergebnis der Transformation
   * wird auf stdout ausgegeben.
   */
  public static void main(String[] args)
      throws MalformedURLException, SAXException {
    if (args.length != 2) {
      System.err.println("Syntax:");
      System.err.println(" java " + BeispielXalan1.class.getName( )
        + " xmlDateiname xsltDateiname");
      System.exit(1);
    }
        
    String xmlDateiname = args[0];
    String xsltDateiname = args[1];
        
    String xmlSystemId = new File(xmlDateiname).toURL().toExternalForm( );
    String xsltSystemId = new File(xsltDateiname).toURL().toExternalForm( );
        
    org.apache.xalan.xslt.XSLTProcessor processor =
      org.apache.xalan.xslt.XSLTProcessorFactory.getProcessor( );
        
    org.apache.xalan.xslt.XSLTInputSource xmlInputSource =
      new org.apache.xalan.xslt.XSLTInputSource(xmlSystemId);
        
    org.apache.xalan.xslt.XSLTInputSource xsltInputSource =
      new org.apache.xalan.xslt.XSLTInputSource(xsltSystemId);
        
    org.apache.xalan.xslt.XSLTResultTarget ergebnisBaum =
      new org.apache.xalan.xslt.XSLTResultTarget(System.out);
        
    processor.process(xmlInputSource, xsltInputSource, ergebnisBaum);
  }
}

 

Imports and the class declaration come first, followed by checking that both arguments were supplied. If so, the XML and XSLT filenames are converted into System identifier values:

String xmlSystemId = new File(xmlDateiname).toURL().toExternalForm( );
String xsltSystemId = new File(xsltDateiname).toURL().toExternalForm( );

System identifiers belong to the XML specification and mean exactly the same as URI (Uniform Resource Identifier). A URL (Uniform Resource Locator) is a specific URI and works with methods accepting system identifiers. For Java code, a platform-specific filename such as C:\daten\simpel.xml must first become file:///C:/daten/simpel.xml for most XML APIs. This code performs the conversion on Unix, Windows and other Java platforms. Manually prefixing file:/// may make code nonportable. The documentation for java.io.File explicitly states that method toURL( ) creates a system-dependent URL, so results differ outside Windows. On Windows it actually creates a nonstandard URL with one slash, which still works in Java: file:/C:/daten/simpel.xml.

With system identifiers for both inputs, create an XSLT processor instance:

org.apache.xalan.xslt.XSLTProcessor processor =
     org.apache.xalan.xslt.XSLTProcessorFactory.getProcessor( );

XSLTProcessor is an interface, and XSLTProcessorFactory creates instances of classes implementing it. Since Xalan is open source, we can easily discover that XSLTEngineImpl implements interface XSLTProcessor. However, avoid depending on a specific implementation.

The next lines create XSLTInputSource objects, one for XML and another for XSLT:

org.apache.xalan.xslt.XSLTInputSource xmlInputSource =
     new org.apache.xalan.xslt.XSLTInputSource(xmlSystemId);

org.apache.xalan.xslt.XSLTInputSource xsltInputSource =
     new org.apache.xalan.xslt.XSLTInputSource(xsltSystemId);

XSLTInputSource subclasses org.xml.sax.InputSource, adding the ability to read directly from a DOM node. XSLTInputSource can read XML and XSLT not only from a system ID but also from java.io.InputStream, java.io.Reader, org.w3c.dom.Node or an existing InputSource. The constructor specifies the source, as shown. XSLTInputSource also has a no-argument constructor and get/set methods for each supported source type.

Next, an instance of XSLTResultTarget sends the transformation result to System.out:

org.apache.xalan.xslt.XSLTResultTarget ergebnisBaum =
     new org.apache.xalan.xslt.XSLTResultTarget(System.out);

Like XSLTInputSource, XSLTResultTarget can also wrap an instance of org.w3c.dom.Node, an OutputStream or Writer, a filename (not a system ID!) or an instance of org.xml.sax.DocumentHandler.

The final line tells the processor to perform the transformation:

processor.process(xmlInputSource, xsltInputSource, ergebnisBaum);

SAXON implementation

For comparison, the next example uses SAXON 5.5.1. Its Java package names include “trax”, indicating that this version was moving toward what is called Transformation API for XML (TrAX). The JAXP discussion explains TrAX further. Briefly, it provides a uniform API intended to work with any XSLT processor.

Example: BeispielSaxon.java

package kapitel5;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import org.xml.sax.SAXException;

/**
 * Ein einfaches SAXON-Beispiel. Der Code wurde ursprünglich mit SAXON 5.5.1
 * erstellt.
 */
public class BeispielSaxon {
  
    /**
     * Akzeptiert zwei Kommandozeilenparameter: den Namen der XML-Datei und
     * den Namen des XSLT-Stylesheets. Das Ergebnis der Transformation wird auf stdout
     * ausgegeben.
     */
    public static void main(String[] args)
           throws MalformedURLException, IOException, SAXException {
      if (args.length != 2) {
          System.err.println("Syntax:");
          System.err.println(" java " + BeispielSaxon.class.getName( )
                 + " xmlDateiame xsltDateiname");
          System.exit(1);
      }
             
      String xmlDateiname = args[0];
      String xsltDateiname = args[1];
             
      String xmlSystemId = new File(xmlDateiname).toURL().toExternalForm( );
      String xsltSystemId = new File(xsltDateiname).toURL().toExternalForm( );
             
      com.icl.saxon.trax.Processor processor =
               com.icl.saxon.trax.Processor.newInstance("xslt");
             
      // Anders als Xalan benutzt SAXON die InputSource von SAX. Xalan
      // dagegen verwendet seine eigene Klasse, XSLTInputSource
      org.xml.sax.InputSource xmlInputSource =
               new org.xml.sax.InputSource(xmlSystemId);
      org.xml.sax.InputSource xsltInputSource =
               new org.xml.sax.InputSource(xsltSystemId);
             
      com.icl.saxon.trax.Result ergebnis =
               new com.icl.saxon.trax.Result(System.out);
             
      // erzeuge neues kompiliertes stylesheet
      com.icl.saxon.trax.Templates templates =
               processor.process(xsltInputSource);
             
      // erzeuge einen Transformer für eine einzelne Transformation
      com.icl.saxon.trax.Transformer trans = templates.newTransformer( );
      trans.transform(xmlInputSource, ergebnis);
    }
}

SAXON begins just like Xalan: after the class declaration, arguments are checked and converted to system IDs. These XML and XSLT IDs are wrapped by org.xml.sax.InputSource as follows:

org.xml.sax.InputSource xmlInputSource =
     new org.xml.sax.InputSource(xmlSystemId);
org.xml.sax.InputSource xsltInputSource =
     new org.xml.sax.InputSource(xsltSystemId);

This is almost identical to Xalan, except that Xalan uses XSLTInputSource instead of InputSource. As noted, XSLTInputSource merely subclasses InputSource to add DOM-node input. SAXON can also read a DOM node, though its approach differs slightly.

Creating a Result object sets the destination of the XSLT result tree, here System.out:

com.icl.saxon.trax.Result ergebnis =
    new com.icl.saxon.trax.Result(System.out);

The stylesheet is then compiled into an object that can be reused by concurrent threads.

com.icl.saxon.trax.Templates templates =
    processor.process(xsltInputSource);

XML websites typically generate data dynamically but reuse stylesheets. Common headers, footers and navigation serve many pages. For best performance, process stylesheets once and reuse their instances for concurrent clients. Thread safety of templates is therefore important.

An instance of class Transformer performs the transformation. Unlike the stylesheet, it cannot serve concurrent clients and is not thread-safe. In a servlet, the instance of Transformer must be recreated for each call to doGet or doPost. Our example does this:

com.icl.saxon.trax.Transformer trans = templates.newTransformer( );
trans.transform(xmlInputSource, ergebnis);

SAXON, Xalan or TrAX?

SAXON and Xalan have many similarities. This eases learning but does not make code portable. Using either interface directly binds you to that implementation unless you rewrite your application.

Another option is a facade providing a consistent interface over both processors. Unfortunately it must be adapted for each new processor, making rapid XSLT changes hard for an individual or organization to follow.

If the facade were an open standard with enough users, processor vendors would face pressure to support the common API instead. TrAX began in spring 2000 to define a consistent API for every XSLT processor.

One of TrAX’s proponents also implemented a major processor, so it was quickly accepted as a future de facto standard, much like SAX.

   

 

 

 

back to top