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

What's New
XSLTC Translets

Overview
Getting Started

FAQs

Sample Apps
Command Line

Usage Patterns

TrAX
API (Javadoc)

Extensions
Extensions Library

Release Notes

Xalan 2 Design
XSLTC Design

Bugs
Testing

Credits
XSLTC Credits

Basic steps
 
  1. Instantiate a TransformerFactory
  2. Process the stylesheet and generate a Transformer
  3. Perform the transformation

The following example illustrates the three basic steps involved in performing a transformation.

// 1. Instantiate a TransformerFactory.
javax.xml.transform.TransformerFactory tFactory = 
                  javax.xml.transformerTransformerFactory.newInstance();

// 2. Use the TransformerFactory to process the stylesheet Source and
//    generate a Transformer.
javax.xml.transform.Transformer transformer = tFactory.newTransformer
                (new javax.xml.transform.stream.StreamSource("foo.xsl");

// 3. Use the Transformer to transform an XML Source and send the
//    output to a Result object.
transformer.transform
    (new javax.xml.transform.stream.StreamSource("foo.xml"), 
     new javax.xml.transform.stream.StreamResult( new
                                  java.io.FileOutputStream("foo.out")));
NoteFor a working example of this model at its simplest, see SimpleTransform.java in the java/samples/SimpleTransform subdirectory.

1. Instantiate a TransformerFactory
 

TransformerFactory is an abstract class with a static newInstance() method that instantiates the concrete subclass designated by the javax.xml.transform.TransformerFactory system property.

The default setting for this system property is org.apache.xalan.processor.TransformerFactoryImpl.


2. Use the TransformerFactory to process the stylesheet Source and produce a Transformer
 

The TransformerFactory newTransformer(Source xslSource) method processes the stylesheet Source into a Templates object and returns a Transformer that you can use to perform a transformation (apply the Templates object to an XML Source).

You may provide the stylesheet Source in the form of a stream of XML markup (StreamSource), a DOM Node (DOMSource), or a SAX InputSource (SAXSource). To specify a StreamSource, you may use a system ID or file name (using URI syntax), a java.io.InputStream, or a java.io.Reader. The use of DOMSource and SAXSource are illustrated in subsequent sections.

NoteIf you plan to use the stylesheet Source to transform multiple XML Sources, you should use the TransformerFactory newTemplates(Source xslSource) method to explicitly generate a Templates object. For each transformation, use the Templates object to generate a new Transformer. For the details, see Multithreading.

3. Use the Transformer to perform a transformation
 

Use the Transformer transform(Source xmlSource, Result transformResult) method to transform the XML Source and place the transformation output in a Result object.

Just as with the stylesheet, you can supply the XML Source in the form of a StreamSource, DOMSource, or SAXSource. Likewise, the Result may be a StreamResult, DOMResult, or SAXResult.

For each node in the XML source, the Transformer uses the transformation instructions in the Templates object to determine which template to apply: one of the templates in the Templates object, a default template rule as specified in the XSLT spec, or none.


Plugging in a Transformer and XML parser
 

The Java API for XML Processing interfaces enable you to isolate your application from the internal implementation details of a given Transformer, SAX parser, or DOM parser. For each of these objects, there is an abstract Factory class with a static newInstance() method that instantiates a concrete Factory which wraps the underlying implementation. These newInstance() methods use system property settings to determine which implementation to instantiate.

Xalan-Java is distributed with system property settings for the Xalan XSLT Transformer and the Xerces DOM and SAX parsers. These settings are in xalan.jar in META-INF/services (see src/META-INF/services).

System property
Setting
javax.xml.transform.TransformerFactory
org.apache.xalan.processor.TransformerFactoryImpl
javax.xml.parsers.DocumentBuilderFactory
org.apache.xerces.jaxp.DocumentBuilderFactoryImpl
javax.xml.parsers.SAXParserFactory
org.apache.xerces.jaxp.SAXParserFactoryImpl

You can change any of these settings as follows (in order of precedence):

  1. Set the system property from the command line when you launch Java or from within your application.

  2. Set the system property in jaxp.properties in the JAVA_HOME/lib directory, where JAVA_HOME is the root of the JDK.

  3. Revise the entry in src/META-INF/services and rebuild xalan.jar.

For example, to use the Crimson XML parser in place of the Xerces XML parser, place Crimson on the class path and set the javax.xml.parsers.SAXParserFactory system property to org.apache.crimson.jaxp.SAXParserFactoryImpl.

For more information about the mechanism used to determine system property values and how you can plug other implementations into your applications, see "Section 3: Plugability Layer" in the Java API for XML Processing at JSR-000063 1.1.


Setting output properties in your stylesheets
 

Output properties for XML, HTML, and Text transformation output are defined in property files in the org.apache.xalan.templates package.

You can change these settings as follows:

  1. Declare the xalan namespace in your stylesheet element (xmlns:xalan="http://xml.apache.org/xslt").

  2. Use the namespace prefix you assign (for example, "xalan") to redefine properties of interest in the stylesheet xsl:output element (for example, xalan:indent-amount="5").

The following stylesheet fragment declares the xalan namespace and sets indent-amount to 2:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xslt">
                
  <xsl:output method="xml" 
              encoding="UTF-8"
              indent="yes" 
              xalan:indent-amount="2"/>

If you want to change the property settings globally, edit the values in the property files in src/org/apache/xalan/templates, and use Ant to rebuild xalan.jar.

The properties files define the following properties:

output_xml.properties:

Property  Default value 
xalan:indent-amount 
xalan:content-handler  org.apache.xalan.serialize.SerializerToXML 

output_html.properties:

Property  Default value 
xalan:indent-amount 
xalan:content-handler  org.apache.xalan.serialize.SerializerToHTML 
entities  HTMLEntities.res 
xalan:use-url-escaping  yes 
NoteYou can also create your own HTML entity file (mapping characters to entities) or edit src/org/apache/xalan/serialize/HTMLEntities.res and rebuild xalan.jar.

output_text.properties:

Property  Default value 
xalan:content-handler  org.apache.xalan.serialize.SerializerToText 

See also Release Notes: Output Properties.


Working with embedded stylesheets
 

An XML Source may include an xml-stylesheet processing instruction which identifies the stylesheet to be used to process the document. As indicated by the processing instruction href attribute, the stylesheet itself may be embedded in the XML document or located elsewhere.

Suppose you have an XML document (foo.xml) with the following xml-stylesheet processing instruction:

<?xml-stylesheet type="text/xml" href="foo.xsl"?>

The following fragment, uses this instruction to locate the stylesheet (foo.xsl in the same directory as foo.xml) and create a Templates object. Note the use of the TransformerFactory getAssociatedStylesheet() in step 2a.

NoteAn XML document may include more than one xml-stylesheet processing instruction, hence the support for working with multiple stylesheets. If more than one stylesheet is returned, the other stylesheets are imported into the first stylesheet.
// 1. Instantiate the TransformerFactory.
javax.xml.transform.TransformerFactory tFactory = 
                    javax.xml.transform.TransformerFactory.newInstance();
// 2a. Get the stylesheet from the XML source.
String media = null , title = null, charset = null;
javax.xml.transform.Source stylesheet = tFactory.getAssociatedStylesheet
                   (new StreamSource("foo.xml"),media, title, charset);

// 2b. Process the stylesheet and generate a Transformer.
Transformer transformer = tFactory.newTransformer(stylesheet);

// 3. Use the Transformer to perform the transformation and send the
//    the output to a Result object.
transformer.transform
             (new javax.xml.transform.stream.StreamSource("foo.xml"),
              new StreamResult (new java.io.FileOutputStream("foo.out")));

For a sample that uses this technique, see UseStylesheetPI.

You can also instruct the command-line utility to use stylesheet processing instructions:

  1. Include the -in flag with an XML source that contains a stylesheet processing instruction.

  2. Do not include the -xsl flag.

Serializing output
 

In some cases, you may want to "transform" a DOM tree into a stream, which the XML community calls serialization. TRaX (Transformation API for XML) and the Xalan-Java Transformer implementation provide direct support for this operation. Simply use the TransformerFactory newTransformer() method (no arguments) to create a Transformer that you can use to "copy" a DOMSource to a StreamResult. For examples, see Examples.exampleDOM2DOM(), Examples.exampleSerializeNode(), and Examples.exampleAsSerializer() in the trax sample.


Setting stylesheet parameters
 

An XSLT stylesheet may include parameters that are set at run time each time a transformation is performed. To set a stylesheet parameter, use the Transformer setParameter(String name, Object value) method. For a working example, see UseStylesheetParam.java in the samples/UseStylesheetParam subdirectory.

You can also set a parameter with the command-line utility by including the -param flag. For example:

java org.apache.xalan.xslt.Process -in foo.xml -xsl foo.xsl -param param1 foobar

where param is the parameter name and foobar is the parameter value. The parameter namespace is null.

NoteXalan-Java 2 processes string parameters. You are no longer required (as you were with Xalan-Java version 1) to enclose strings in single quotes (') as string expressions.

Explicitly working with SAX
 

Xalan-Java uses the SAX event model to process stylesheets, to parse XML input documents, and to produce output. For each of these operations, an XMLReader reads input, firing parse events, and a ContentHandler listens to the XMLReader and executes parse event methods.

When you use the basic procedure described above for performing transformations, Xalan-Java takes care of many of the SAX details under the covers. You are free to make these details explicit, which simply means that you can intervene in the procedure to accommodate the precise environment in which your application operates.

Suppose, for example, you are using a custom XMLReader, perhaps doing more than just parsing static XML documents) to generate Xalan-Java SAX parse events. You might even have a custom reader for producing/processing stylesheets. You can cast the TransformerFactory to a SAXTransformerFactory, which provides access to a TransformerHandler, which you can set as the ContentHandler for this reader.

The following example explicitly sets up the XMLReader and ContentHandlers, and replicates the basic steps described above.

// Instantiate a TransformerFactory.
javax.xml.transform.TransformerFactory tFactory = 
                    javax.xml.transform.TransformerFactory.newInstance();
// Verify that the TransformerFactory implementation you are using
// supports SAX input and output (Xalan-Java does!).
if (tFactory.getFeature(javax.xml.transform.sax.SAXSource.FEATURE) && 
    tFactory.getFeature(javax.xml.transform.sax.SAXResult.FEATURE))
  { 
    // Cast the TransformerFactory to SAXTransformerFactory.
    javax.xml.transform.sax.SAXTransformerFactory saxTFactory = 
                   ((javax.xml.transform.SAXTransformerFactory) tFactory);
    // Create a Templates ContentHandler to handle parsing of the 
    // stylesheet.
    javax.xml.transform.sax.TemplatesHandler templatesHandler = 
                                        saxTFactory.newTemplatesHandler();

    // Create an XMLReader and set its ContentHandler.
    org.xml.sax.XMLReader reader = 
                   org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    reader.setContentHandler(templatesHandler);
    
    // Parse the stylesheet.                       
    reader.parse("foo.xsl");

    // Get the Templates object (generated during the parsing of the stylesheet)
    // from the TemplatesHandler.
    javax.xml.transform.Templates templates = 
                                          templatesHandler.getTemplates();
    // Create a Transformer ContentHandler to handle parsing of 
    // the XML Source.  
    javax.xml.transform.sax.TransformerHandler transformerHandler 
                           = saxTFactory.newTransformerHandler(templates);
    // Reset the XMLReader's ContentHandler to the TransformerHandler.
    reader.setContentHandler(transformerHandler);

    // Set the ContentHandler to also function as a LexicalHandler, which
    // can process "lexical" events (such as comments and CDATA). 
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", 
                        transformerHandler);

    // Set up a Serializer to serialize the Result to a file.
    org.apache.xalan.serialize.Serializer serializer = 
    org.apache.xalan.serialize.SerializerFactory.getSerializer
    (org.apache.xalan.templates.OutputProperties.getDefaultMethodProperties
                                                                   ("xml"));
    serializer.setOutputStream(new java.io.FileOutputStream("foo.out"));
    // The Serializer functions as a SAX ContentHandler.
    javax.xml.transform.Result result =
      new javax.xml.transform.sax.SAXResult(serializer.asContentHandler());
    transformerHandler.setResult(result);
      
    // Parse the XML input document.
    reader.parse("foo.xml");

Using transformation output as input for another transformation
 

You can chain together a series of transformations such that the output of each transformation provides input for the next transformation. Xalan-Java supports two basic strategies for chaining a series of transformations:

  • Use the SAXTransformerFactory to process the stylesheet and create a TransformerHandler for each transformation. Then you can set the first TransformerHandler as the ContentHandler for the XMLReader that parses the input, make the second TransformerHandler the ContentHandler for the output of the first TransformerHandler, and so on. For more detail and an example, see the Pipe sample.

  • Use the SAXTransformerFactory to process the stylesheet and create a SAX XMLFilter for each transformation. Set an XMLReader as the parent of the first XMLFilter, the first XMLFilter as the parent of the second XMLFilter, and so on. You launch the series of transformations by instructing the last XMLFilter to parse the XML Source for the first transformation. For more detail and an example, see the UseXMLFilters sample.

Processing and producing DOM trees
 

In some cases, the input and/or desired output for a transformation may be a DOM tree object. The javax.xml.transform.DOM package provides DOMSource and a DOMResult, either or both of which you can use when you perform a transformation.

In some cases, your application provides input in the form of a DOM tree, which accelerates the transformation process, since the input has in effect already been processed. To produce DOM input from a stream, you can use a DocumentBuilderFactory to produce a DocumentBuilder with which you can parse the XML input into a DOM Document, as illustrated below.

// Instantiate a DocumentBuilderFactory.
javax.xml.parsers.DocumentBuilderFactory dfactory =
                    javax.xml.parsers.DocumentBuilderFactory.newInstance();
// Use the DocumentBuilderFactory to provide access to a DocumentBuilder.
javax.xml.parsers.DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
// Use the DocumentBuilder to parse the XML input.
org.w3c.dom.Document inDoc = dBuilder.Parse("foo.xml");

To produce DOM output, simply use a Transformer to transform to a DOMResult object.

// Generate a Transformer.
javax.xml.transform.Transformer transformer = tFactory.newTransformer
                  (new javax.xml.transform.Stream.StreamSource("foo.xsl"));
// Create an empy DOMResult object for the output.
javax.xml.transform.dom.DOMResult domResult =
                                   new javax.xml.transform.dom.DOMResult();
// Perform the transformation.
transformer.transform(new javax.xml.transform.dom.DOMSource(inDoc)
                      domResult;
// Now you can get the output Node from the DOMResult.
org.w3c.dom.Node node = domResult.getNode();
NoteCreate a new DOMResult object or use DOMResult.setNode() to assign a new container each time you want to perform a transformation and place the output in a DOMResult object.

The DOM2DOM illustrates both procedures, and serializes the DOMResult to System.out.


Working with XPath expressions
 

XSLT stylesheets use XPath expressions to select nodes, specify conditions, and generate text for the result tree. XPath provides an API that you can call directly. For example, you may want to select nodes programmatically and do your own processing without a stylesheet.

XPath is an independent entity, with clients other than XSLT processors (such as XPointer). Accordingly, Xalan-Java 2 has packaged XPath as a separate module (org.apache.xpath and its subpackages), although concurrently this module does use some utility classes packaged in org.apache.xalan.utils. The org.apache.xpath.XPathAPI class contains convenience methods that you can use to return single DOM Nodes, NodeIterators, and XObjects. Apart from their own functionality, these methods also provide a path into the lower-level XPath API that you may find useful.

For an example that uses the XPathAPI convenience methods to execute XPath expressions against XML source files, see ApplyXPath.


Using the Xalan-Java applet wrapper
 
  1. Include XSLTProcessorApplet in an HTML client.

  2. Specify the XML source document and XSL stylesheet.

    You can use the DocumentURL and StyleURL PARAM tags or the setdocumentURL() and setStyleURL() methods. If the XML document contains a stylesheet Processing Instruction (PI), you do not need to specify an XSL stylesheet.

  3. Call the transformToHtml() or getHtmlText() method, which performs the transformation and returns the new document as a String.
NoteThe transformToHTML() method takes arguments for the XML source document and XSL stylesheet. The getHtmlText() method takes no arguments: it uses property or parameter settings, as in the example below.

For an example, see the AppletXMLtoHTML sample applet. The <applet> tag is in samples/AppletXMLtoHTML/client.html:

<applet  
    name="xslControl"
    code="org.apache.xalan.client.XSLTProcessorApplet.class"
    archive="../../bin/xalan.jar,../../bin/xerces.jar"
    height="0"
    width"0">
    <param name="documentURL" value="xalanApplets.xml"/>
    <param name="styleURL" value="s1ToHTML.xsl"/>
</applet>

When the user clicks the Transform button, the HTML client calls the getHtmlText() method, and puts the returned HTML text in a frame for the user to view.


Using Xalan-Java in a servlet
 

You can set up a servlet to use Xalan-Java to respond to requests for XML documents by transforming those documents into HTML and serving them to web browsers. To respond to HTTP GET requests, all you need to do is overwrite the HttpServlet doGet() method with a procedure that instantiates a Transformer and uses it to perform a transformation. As the following example shows, you can generate a ResultStream that a PrintWriter writes to the HttpResponse OutputStream, returning the transformation output to the web browser.

public class SampleXSLTServlet extends javax.servlet.http.HttpServlet {
  
  // Respond to HTTP GET requests from browsers.
  public void doGet (javax.servlet.http.HttpServletRequest request,
                     javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.ServletException, java.io.IOException
  {
    // Set content type for HTML.
    response.setContentType("text/html; charset=UTF-8");    
    // Output goes to the response PrintWriter.
    java.io.PrintWriter out = response.getWriter());
    try
    {	
      javax.xml.transform.TransformerFactory tFactory = 
                javax.xml.transform.TransformerFactory.newInstance();
      // Get the XML input document and the stylesheet, both in the servlet
      // engine document directory.
      javax.xml.transform.Source xmlSource = 
                new javax.xml.transform.stream.StreamSource
                             (new java.net.URL("file:foo.xml").openStream());
      javax.xml.transform.Source xslSource = 
                new javax.xml.transform.stream.StreamSource
                             (new java.net.URL("file:foo.xsl").openStream());
      // Generate the transformer.
      javax.xml.transform.Transformer transformer = 
                             tFactory.newTransformer(xslSource);
      // Perform the transformation, sending the output to the response.
      transformer.transform(xmlSource, 
                           new javax.xml.transform.stream.StreamResult(out));
    }
    // If an Exception occurs, return the error to the client.
    catch (Exception e)
    {
      out.write(e.getMessage());
      e.printStackTrace(out);    
    }
    // Close the PrintWriter.
    out.close();
  }  
}

For a working sample, see SimpleXSLTServlet.

In the preceding example, the URLs for the XML document and XSL stylesheet are hardcoded in the servlet. You can also create a servlet that parses the request URL for input parameters specifying the XML document, XSL stylesheet, and any relevant stylesheet parameters. For samples, see UseStylesheetParamServlet and XSLTServletWithParams. For a more robust and complex sample that also employs a properties file to determine which stylesheet to use depending on the client browser/device, see ApplyXSLT.


Creating and using extensions
 

For those cases where you want to be able to call procedural code from within a stylesheet, the Xalan-Java Extensions facility supports the creation of extension elements and extension functions. See Extensions and Extensions samples.


Multithreading
 

A given Templates object may be used repeatedly and even in multiple threads running concurrently for the transformation of XML input, but you should use the Templates object to instantiate a separate Transformer for each transformation you perform. The Templates object is an immutable runtime representation of the structure and content of a stylesheet (which may include and import multiple stylesheet sources). A Transformer, on the other hand, is a lightweight object that tracks state information during the transformation, and should only be used to perform a single transformation.

If you want to perform multiple transformations (sequentially or concurrently) with the same stylesheet instructions, do the following:

  1. Use the TransformerFactory newTemplates(Source xslSource) method to create a Templates object.

  2. For each transformation, use the Templates object newTransformer() method to create a Transformer, and use that Transformer's transform(Source xmlSource, Result transformResult) method to perform the transformation.

For an example, see Examples.exampleUseTemplatesObj() in the trax sample.


Debugger Interface
 

Xalan-Java contains a debugger interface in the org.apache.xalan.xslt.trace package:

  • TraceListener is an interface that debuggers can implement. Or, like the command-line utility, you can use the PrintTraceListener implementation of that interface.

  • You can register a TraceListener with the TraceManager associated with the Transformer that will perform a given transformation.

  • TracerEvent is an event that is passed to the TraceListener.trace function. It is called before a node is 'executed' in the stylesheet.

  • GenerateEvent is an event that is passed to the TraceListener.generated() function. It is called after an event occurs to create something in the result tree.

  • SelectionEvent is an event triggered by the selection of a stylesheet node.

The command-line utility uses the debugger interface when you include one or more of the following switches: -TT, -TG, -TS, -TTC.

Example:

import org.apache.xalan.transformer.TransformerImpl;
import org.apache.xalan.trace.TraceManager;
import org.apache.xalan.trace.PrintTraceListener;
...
// Set up a PrintTraceListener object to print to a file.
java.io.FileWriter fw = new java.io.FileWriter("events.log");
java.io.PrintWriter pw = new java.io.PrintWriter(fw);
PrintTraceListener ptl = new PrintTraceListener(pw);

// Print information as each node is 'executed' in the stylesheet.
ptl.m_traceElements = true;
// Print information after each result-tree generation event.
ptl.m_traceGeneration = true;
// Print information after each selection event.
ptl.m_traceSelection = true;
// Print information whenever a template is invoked.
ptl.m_traceTemplates = true;

// Set up the transformation    
javax.xml.transform.TransformerFactory tFactory = 
                     javax.xml.trnasform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = 
  tFactory.newTransformer(new javax.xml.transform.stream.StreamSource
                                                             ("foo.xsl"));

// Cast the Transformer object to TransformerImpl.
if (transformer instanceof TransformerImpl) {
  TransformerImpl transformerImpl = (TransformerImpl)transformer;
  
  // Register the TraceListener with the TraceManager associated 
  // with the TransformerImpl.
  TraceManager trMgr = transformerImpl.getTraceManager();
  trMgr.addTraceListener(ptl);
  
  // Perform the transformation --printing information to
  // the events log during the process.
  transformer.transform
      ( new javax.xml.transform.stream.StreamSource("foo.xml"), 
        new javax.xml.transform.stream.StreamResult
                                    (new java.io.FileWriter("foo.out")) );
}
// Close the PrintWriter and FileWriter.
pw.close();
fw.close();

For a sample application that uses this technique, see Trace.


Using the Xalan-Java version 1 API
 

The bin directory includes a compatibility jar, xalanj1compat.jar, that lets you rebuild your Xalan-Java 1.x applications to run with Xalan-Java 2. As a point of reference, this JAR includes the API required to recompile the Xalan-Java 1.x core sample applications (excluding the sample extensions) and run them with Xalan-Java 2. To use this compatibility layer with an existing Xalan-Java 1.x application, do the following:

  1. Place xalanj1compat.jar on the system classpath in front of the Xalan-Java 2 xalan.jar (both are in the bin directory).

  2. Recompile your application. It it does not compile, you may be using Xalan-Java 1.x API that the compatibility layer does not support.

  3. Run the recompiled application with xalanj1compat.jar on the system classpath in front of the Xalan-Java 2 xalan.jar.

We urge our Xalan-Java 1.x users to start using Xalan-Java 2. That is where we are concentrating our efforts to improve performance and fix any outstanding bugs. To see what portion of the Xalan-Java 1.x API we have included in xalanj1compat.jar, see Xalan-Java 1 compatibility Javadoc. For example, the compatibility layer does not support the use of Xalan-Java 1.x extensions. If you feel that we should extend our compatibility JAR to support additional Xalan-Java 1.x API calls, please let us know exactly what you would like to see.



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