http://xml.apache.org/http://www.apache.org/http://www.w3.org/

What's New
DTM
XSLTC Translets

Overview
Getting Started

FAQs

Sample Apps
Command Line

Usage Patterns
Features

TrAX
API (Javadoc)

Extensions
Extensions Library

Release Notes

Xalan 2 Design
XSLTC Design

Bugs
Testing
Builds

Credits
XSLTC Credits

See also: XSLTC Design

Introduction
 

XSLTC provides a compiler and a runtime processor. Use the compiler to compile an XSL stylesheet into a translet (i.e. a set of Java classes). Use the runtime processor to apply the translet to an XML document and perform a transformation.

NoteTo compile and run translets you must have a JDK or a JRE 1.2 or higher.

Setting the system classpath for XSLTC
 

The jar file structure of the XSLTC component has changed. In the original structure the xsltc.jar file contained only XSLTC classes, and the other support jar files needed to be in the user's class path. If you want to use this model refer to the subsection below 'Unbundled System Classpath'. In the newer model, all of the support classes have been bundled with the XSLTC classes into one xsltc.jar file. The size of the bundled jar file is significantly larger, around 1.2MB. However classpath setup is significantly easier. Refer to the subsection 'Bundled System Classpath' below.


Bundled System Classpath
 

To use this newer approach, simply put xsltc.jar in your classpath. No need to mention the others (BCEL.jar, JLex.jar, regexp.jar, java_cup.jar, runtime.jar).

NoteIn order to compile and run translets you must have a JAXP-compliant XML parser installed. Our distribution includesXerces (just include xercesImpl.jar and xml-apis.jar in your class path).

Unbundled System Classpath
 

To compile translets, run translets, and use the XSLTC API, put the following on the system classpath:

Classes or JAR  To compile a translet  To run a translet 
the translet    required 
xsltc.jar  required  required 
runtime.jar  required  required 
BCEL.jar  required   
JLex.jar  required   
java_cup.jar  required   
regexp.jar  required   

The JAR files listed above are installed in the Xalan-Java bin directory. The translet is the set of class files or the JAR file that you generate with the compiler; see Compiling translets.


Compiling translets from the command line
 

The XSLT Compiler is a Java-based tool for compiling XSLT stylesheets into lightweight and portable Java byte codes called translets.

To run the compiler from the command line or from a script, set the classpath and run the class org.apache.xalan.xsltc.cmdline.Compile. The synopsis of the options and arguments accepted by this class is shown below.

Synopsis
 

java org.apache.xalan.xsltc.cmdline.Compile
    [-o <output>] [-d <directory>] [-j <jarfile>]
    [-p <package name>] [-n] [-x] [-v] [-u] [-h]
    {<stylesheet> | -i }


Flags and arguments
 

The following flags and arguments are supported:

-o <output>
   Specifies the name of the generated translet class.
   If you omit this argument, the translet class is
   named <stylesheet>. Translets are written as 
   .class files.

-d <directory>
   Specifies the destination directory. If you omit
   this argument, the translet class files are placed
   in the current working directory.

-j <jarfile>
   Outputs the generated translet class files into a 
   jar file named <jarfile>.jar. When this option is 
   used, only the jar file is output.

-p <package name>
   Specifies a package name for the generated translet
   classes.

-n Enables template inlining (default behavior better on average).

-x Turns on additional debugging messages.

-s Disables calling System.exit

-u  <stylesheet>
  Specifies the stylesheet with a URI such as 
  'http://myserver/stylesheet1.xsl'.

   <stylesheet>
   (No flag) The pathname of the stylesheet file.

-i Force input to be read from stdin

-v Prints version of compiler

-h Prints usage statement

Examples
 

The following examples assume that you have already set the classpath to include the translet and the required JAR files (see setting the system classpath).

Example 1: Creating a translet from the hamlet.xsl stylesheet.

java org.apache.xalan.xsltc.cmdline.Compile
     hamlet.xsl

Example 1 produces a set of class files such as hamlet.class, hamlet$0.class, hamlet$1.class.

Example 2: Outputting to a JAR file.

java org.apache.xalan.xsltc.cmdline.Compile
     -j hamlet.jar hamlet.xsl

Example 2 produces hamlet.jar, which contains the translet class files.

Example 3: Specifying the translet class name.

java org.apache.xalan.xsltc.cmdline.Compile
     -o newhamlet hamlet.xsl

Example 3 producs a set of class files such as newhamlet.class, newhamlet$0.class, etc., rather than hamlet.class, hamles$0.class, etc.

Example 4: Compiling multiple stylesheets.

java org.apache.xalan.xsltc.cmdline.Compile
     hamlet1.xsl hamlet2.xsl hamlet3.xsl

Example 4 produces three translets and set of class files derived from the three stylesheets.

Example 5: Package Specification.

java org.apache.xalan.xsltc.cmdline.Compile
     -p com.mycompany.translets hamlet.xsl

Example 5 produces a set of class files such as com/mycompany/translets/hamlet.class, com/mycompany/translets/hamlet$0.class', etc.



Running translets from the command line
 

The XSLT runtime processor is a Java-based tool for transforming XML document files using a translet (compiled stylesheet).

The XSLT processor can be run on any platform including UNIX, Windows, NT, Mac that supports Java, including a Palm Pilot with J2ME CLDC (Java 2 Micro Edition, Connected Limited Device Configuration).

To run a translet from the command line or a script, set the classpath (be sure to include the translet) and run the translet with the appropriate flags and arguments (described below).

Synopsis
 

java org.apache.xalan.xsltc.cmdline.Transform
     [-j <jarfile>] [-x] [-s] {-u <document_url> | <document>} <class>
     [<name1>=<value1> ...]


Flags and arguments
 

The following flags and arguments are supported:


-j Specifies <jarfile> from which to load translet.

-x Turns on debugging messages.

-s Disables calling System.exit

-u Specifies the XML input <document> with a URI,
   such as 'http://myserver/hamlet.xml'.		

Arguments wirhout flags:

   <document>     		
   Filename of the XML input document. 
   
   <document_url>     	
   URI of the XML input document (see the -u flag above). 

   <class>
   The translet that performs the transformation. The translet
   may take a set of stylesheet parameters specified as
   name-value pairs. The format for a name-value pair is
   <name>=<value>.

Examples
 

The following examples assume that you have already set the classpath to include the translet and the required JAR files (see setting the system classpath).

A possible variation: You have set the classpath to include the required JAR files, but when you run the translet, you use the java -cp flag to add the current working directory (containing the translet class files you have just generated) to the classpath.

Windows: java -cp .;%CLASSPATH% ...
UNIX:      java -cp .:$CLASSPATH ...

Example 1: Processing an XML document.

java org.apache.xalan.xsltc.cmdline.Transform
     hamlet.xml hamlet

Example 1 uses the specified translet (hamlet) to transform the specified XML input document (hamlet.xml). The XML input document is in the current working directory. The translet was created by using org.apache.xalan.xslt.cmdline.Compile to compile an XSL stylesheet (hamlet.xsl).

Example 2: Passing stylesheet parameters to the translet.

java org.apache.xalan.xsltc.cmdline.Transform
     hamlet.xml hamlet
     speaker=HAMLET 'scene=SCENE IV'

Example 2 passes "HAMLET" to the stylesheet for the stylesheet parameter named speaker, and "SCENE IV" for the stylesheet parameter named scene. The second name-value pair was placed in single quotes to specify a value containing a space.

Example 3: Processing an XML input document specified with a URI.

java org.apache.xalan.xsltc.cmdline.Transform
     -u http://zarya.east/test.xml hamlet

Example 3 applies the translet (hamlet) to the XML input document (http://zarya.east/test.xml hamlet). Inclusion of the flag (-u) is optional.



Calling XSLTC with the TrAX/JAXP API
 

XSLTC translets are integrated with the TrAX/JAXP 1.1 API. See The Translet API & TrAX. Accordingly, it is now possible to set a system property and use a TransformerFactory to generate a Transformer that performs a transformation by compiling and running a translet.

When you use the JAXP 1.1 API to run Xalan-Java, the javax.xml.transform.TransformerFactory system property is set to org.apache.xalan.processor.TransformerFactoryImpl. As it currently stands, this Xalan implementation of TransformerFactory always uses the Xalan Transformer to perform transformations. To use translets to perform transformations, set this system property to org.apache.xalan.xsltc.trax.TransformerFactoryImpl. For information on setting this and related system properties designating XML parsere and XSL transformer, see Plugging in a Transformer and XML parser.

To Use the JAXP 1.1 API to perform transformations with translets do the following:

  1. Set the javax.xml.transform.TransformerFactory system property as indicated above.

  2. Instantiate a TransformerFactory.

  3. Assuming you want to perform a series of transformations with the same translet, use the TransformerFactory and a StreamSource XSL stylesheet to generate a Templates object (the translet). If you are performing a single transformation, use the TransformerFactory and the StreamSource object to instantiate a Transformer.

  4. Perform the transformation, using a StreamSource object for the XML input and a StreamResult object to hold the transformation output.
Examples
 

Example 1: Using a translet/Templates object for multiple transformations

import java.util.Properties;
import javax.xml.transform.Transformer;
import java.io.FileOutputStream;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Templates;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
...
// Set the TransformerFactory system property.
// Note: For more flexibility, load properties from a properties file.
String key = "javax.xml.transform.TransformerFactory";
String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
...
String xslInURI;
// Instantiate the TransformerFactory, and use it along with a SteamSource
// XSL stylesheet to create a translet as a Templates object.
TransformerFactory tFactory = TransformerFactory.newInstance();
Templates translet = tFactory.newTemplates(new StreamSource(xslInURI));
...
String xmlInURI;
String htmlOutURI;
...
// For each transformation, instantiate a new Transformer, and perform
// the transformation from a StreamSource to a StreamResult;
Transformer transformer = translet.newTransformer();
transformer.transform(new StreamSource(xmlInURI),
                      new StreamResult(new FileOutputStream(htmlOutURI)));
...

For a working sample that illustrates this usage pattern, see JAXPTransletOneTransformation.

Example 2: Compiling a translet/Templates object for a single transformation

import java.util.Properties;
import javax.xml.transform.TransformerFactory;
import java.io.FileOutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
...
// Set the TransformerFactory system property.
// Note: For more flexibility, load properties from a properties file.
String key = "javax.xml.transform.TransformerFactory";
String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
...
String xslInURI;
String xmlInURI;
String htmlOutURI;
// Instantiate the TransformerFactory, and use it along with a SteamSource
// XSL stylesheet to create a Transformer.
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslInURI));
// Perform the transformation from a StreamSource to a StreamResult;
transformer.transform(new StreamSource(xmlInURI),
                      new StreamResult(new FileOutputStream(htmlOutURI)));

For a working sample that illustrates this usage pattern, see JAXPTransletMultipleTransformations.



Calling XSLTC with the native API
 

This section demonstrates how to use the native XSLTC API in a standalone Java application.

Processing an XML document with a translet involves three main steps:

  1. Compile the stylesheet to a translet.
  2. Parse the input XML document.
  3. Use the translet to transform the XML document.
Code overview
 

XsltApp.java illustrates the basic structure for coding a transformation with the native XSLTC API. In the following listing, the method for performing each of the three steps is an empty shell. The methods are filled in the listings in subsequent sections.

import org.apache.xalan.xsltc.Translet;
import org.apache.xalan.xsltc.dom.DOMImpl;

public class XsltApp {
  public static void main(String[] args) {
    XsltApp proc = new XsltApp();
    proc.run(args);
  }

  public void run(String[] args) {
    if (args.length != 2) {
      System.err.println("Usage:\n\tprocessor <xmlfile> <xslfile>" +
            "\n\n\twhere <xmlfile> = xml input filename, and" +
            "\n\t      <xslfile> = stylesheet filename.");
      System.exit(1);
    }
    String xmldocFilename     = args[0];
    String stylesheetFilename = args[1];

    // Compile the stylesheet to a translet
    Translet translet = compileStylesheet(stylesheetFilename);

    // Parse the input XML document
    DOMImpl dom = getDOM(xmldocFilename);

    // Transform the XML document against the translet
    doTransform(translet, dom);
    System.exit(0);
  }
  
  // compile the stylesheet [Empty shell: see below]
  private Translet compileStylesheet(String stylesheetName) { return null; }

  // parse the input XML document [Empty shell: see below]
  private DOMImpl getDOM(String xmldocname) { return null; }

  // transform the XML document [Empty shell: see below]
  private void doTransform(Translet translet, DOMImpl dom) { }
}

XsltApp takes two command line arguments: the input XML document filename, and the XSL stylesheet filename. The public run() method processes the commandline args, and then carries out the three steps.

The first step is accomplished by calling the compileStylesheet() method. This method takes the stylesheet filename as input (String), and returns an instance of the translet, as type org.apache.xalan.xsltc.Translet.

The input XML document now needs to be parsed. This is accomplished by the getDOM() method. This method takes the XML document's filename (String) and returns the Document Object Model for the document, as an object of type org.apache.xalan.xsltc.dom.DOMImpl.

Finally, the transformation prescribed by the stylesheet is carried out by calling the doTransform() method. This method takes the translet (compiled stylesheet) and the dom (Document Object Model for the XML document) as input parameters. In this example, the results of the transformation are output to standard output, so this method returns nothing.

If all three steps are carried out successfully, the application exits with a successful (zero) value.

The following sections examine each of the three steps in detail.


1. Compiling the Stylesheet to a Translet
 

The 'compileStylesheet' method:

import java.io.File;
import java.net.MalformedURLException; 
import org.apache.xalan.xsltc.compiler.XSLTC;
...
  private Translet compileStylesheet(String stylesheetName) {
    Translet retval = null;
    String transletName = stylesheetName.substring(0,
                              stylesheetName.indexOf('.'));
    try {
      XSLTC xsltc = new XSLTC();
      xsltc.init();
      File stylesheet = new File(stylesheetName);
      xsltc.compile(stylesheet.toURL());
      Class clazz = Class.forName(transletName);
      retval = (Translet)clazz.newInstance();
    } 
    catch (MalformedURLException e) {
      System.err.println("Could not create URL to stylesheet file: " +
                          stylesheetName + ".\n" + e.getMessage());
      System.exit(1);
    } 
    catch (ClassNotFoundException e) {
      System.err.println("Could not find class file: " +
                          transletName + ".class .\n" + e.getMessage());
      System.exit(1);
    } 
    catch (InstantiationException e) {
      System.err.println("Could not instantiate class file: " +
                          transletName + ".class .\n" + e.getMessage());
      System.exit(1);
    } 
    catch (IllegalAccessException e) {
      System.err.println("Could not instantiate class file: " +
            transletName + ".class, illegal access.\n" + e.getMessage());
      System.exit(1);
    }
    return retval;
  }

This method reads in the stylesheet file, compiles it to Java bytecodes (the translet), and then writes the bytecodes to the filesystem, as a series of .class files. Their base name is derived from the name of the stylesheet.

The XSLT compiler object (org.apache.xalan.xsltc.compiler.XSLTC), is created, initialized and then its compile() method is called passing in a URL to the stylesheet itself. Once the .class files have been written, the translet is instantiated using Java reflection to create the Class and then a new instance of the Class as 'retval' of type org.apache.xalan.xsltc.Translet.

Notice all of the various exceptions that could be thrown in the process have been handled with explicit warning messages and a System.exit with a non-zero return value. In your applications, you may want to handle these exceptions differently.


2. Parsing the XML Document
 

Parsing the input XML document is handled in the getDOM() method:

import java.io.IOException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xalan.xsltc.compiler.Constants;
import org.apache.xalan.xsltc.dom.DTDMonitor;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;
...
  private DTDMonitor _dtdMonitor = null;

  private DOMImpl getDOM(String xmldocname) {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
      factory.setFeature(Constants.NAMESPACE_FEATURE, true);
    } 
    catch (Exception e) {
      factory.setNamespaceAware(true);
    }
    final DOMImpl dom = new DOMImpl();
    dom.setDocumentURI(xmldocname);
    XMLReader reader = null;
    SAXParser parser = null;
    _dtdMonitor = new DTDMonitor();
    try {
      parser = factory.newSAXParser();
      reader = parser.getXMLReader();
      reader.setContentHandler(dom.getBuilder());
      _dtdMonitor.handleDTD(reader);
      reader.parse(xmldocname);
    } 
    catch (ParserConfigurationException e) {
      System.err.println("SAX Parser is not configured properly.\n"+
                          e.getMessage());
      System.exit(1);
    } 
    catch (SAXException e ) {
      System.err.println("SAX Parser could not be created.\n"+
                          e.getMessage());
      System.exit(1);
    } 
    catch (IOException e ) {
      System.err.println("XML Reader could not read xml document '"+
                          xmldocname + "'," + e.getMessage());
      System.exit(1);
    }
    return dom;
  }

The method parses the input XML document and creates a Document Object Model to return to the run() method for later use. To parse the document we use a javax.xml.parsers.SAXParser, from the JAXP. The JAXP model uses a factory method; accordingly we first create the factory, which is of type javax.xml.parsers.SAXParserFactory. After configuring the factory to handle namespaces, the procedure gets an org.xml.sax.XMLReader from the SAXParser. The reader is registered with the class DTDMonitor, and then the reader is instructed to parse the XML document. The DOMImpl object is returned to the main() method.

NoteBefore the document is parsed, the DOMImpl is configured with the XML document's URI with a call to the setDocumentURI() method. This is necessary to define the origin of the document from which the DOM tree is built. This information is needed for xsl:import, xsl:include, and the document() function.

3. Doing the Transformation
 

Now everything is set to carry out the XSL transformation. The doTransform() method takes a reference to the Translet object generated from the stylesheet, and the DOMImpl object created from the XML document.

import java.io.IOException;
import org.apache.xalan.xsltc.runtime.DefaultSAXOutputHandler;
import org.apache.xalan.xsltc.runtime.TextOutput;
import org.apache.xalan.xsltc.runtime.AbstractTranslet;
import org.apache.xalan.xsltc.TransletException;
...
  private void doTransform(Translet translet, DOMImpl dom) {
    DefaultSAXOutputHandler outputhandlr = null;
    TextOutput textoutput = null;
    try {
      outputhandlr= new DefaultSAXOutputHandler(System.out, "utf-8");
      textoutput = new TextOutput(outputhandlr, "utf-8");
    } 
    catch (IOException e) {
      System.err.println("Could not create SAX Output Handler."+
                          e.getMessage());
      System.exit(1);
    }
  
    // for XSL keys
    AbstractTranslet absTranslet = (AbstractTranslet)translet;
    absTranslet.setIndexSize(dom.getSize());
    _dtdMonitor.buildIdIndex(dom, 0, absTranslet);

    try {
      absTranslet.transform(dom, textoutput);
    } 
    catch (TransletException e) {
      System.err.println("Could not transform XML document."+
                          e.getMessage());
      System.exit(1);
    }
  }

The Translet's transform() method takes two arguments: the DOMImpl reference created in the getDOM() method, and an xsltc.runtime.TextOutput object. TextOutput is a ContentHandler wrapper class that implements the xsltc.TransletOutputHandler interface. In this example, the content handler (DefaultSAXOutputHandler) is wrapped.

Translet is an interface. AbstractTranslet is a class that implements that interface. Before the transform() method is called, setIndexSize(int) is called to pass in the maximum DOM size to the translet and the DTDMonitor is called to build the node index that the Key (xsl:key implementation) class uses. This is a general case, if you are not using keys, then you do not need to set the index size, consequently you would not need to work with the AbstractTranslet either. In that case, you can use the Translet directly by calling translet.transform(dom, textoutput).


Conclusion
 

The native XSLT compiler API provides a way to compile an XSL stylesheet into a translet. The translet can then be used to transform the DOMImpl of an input XML document. This example demonstrated how to compile a stylesheet into a translet, parse an input XML document, and then transform the XML document using the translet.



XSLTC usage constraints
 

See Conformance issues and Known problems.



Copyright © 2002 The Apache Software Foundation. All Rights Reserved.