Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Tip: XSL transformations to and from a SAX stream

Integrate XSL transformations into your SAX applications

Nicholas Chase (nicholas@nicholaschase.com), President, Chase and Chase, Inc.
Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of Site Dynamics Interactive Communications in Clearwater, FL, USA, and is the author of three books on Web development, including Java and XML From Scratch (Que) and the upcoming Primer Plus XML Programming (Sams). He loves to hear from readers and can be reached at nicholas@nicholaschase.com.

Summary:  The Transformation API for XML (TrAX) simplifies the process of performing XSL transformations by creating a situation where you only need to create the source, style, and result objects, then manipulate them using a Transformer object. When sources and results are DOM nodes or files, it's easy; but what if you want to transform to or from a SAX stream? This tip shows you how to use SAX streams as both the source and destination of an XSL transformation.

View more content in this series

Date:  01 Jul 2002
Level:  Intermediate
Also available in:   Japanese

Activity:  11941 views
Comments:  

Note: This tip uses JAXP. The classes are also part of the Java 2 SDK 1.4, so if you have 1.4 installed, you don't need any additional software. (See Resources for the Xalan-J transformation engine.)

Using TrAX

To perform a transformation using TrAX, you need to define the source, result, and XSL stylesheet, then create a Transformer and use it to actually perform the transformation. You can view the coding for this in Listing 1.

In this case, you create the Source and Result using the StreamSource and StreamResult objects, which take as their arguments the URI for files.

In order to use SAX as input or output, you need to change the way you create the Source and Result.


A SAX stream as the Source object

Now that you have the basic foundation, let's look at using a SAX stream as the input for the transformation:


Listing 2. A SAX stream as input
                

...
import javax.xml.transform.sax.SAXSource;

import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class TransformSAX extends Object {
  public static void main (String args[]) throws Exception
  {
    try {
       String XMLFileName = "mySource.xml";
       String OutputFileName = "myResult.xml";
       String StyleFileName = "myStyle.xsl";
         
       String parserClass = 
          "org.apache.crimson.parser.XMLReaderImpl";
       XMLReader reader = 
          XMLReaderFactory.createXMLReader(parserClass);
       Source source = 
          new SAXSource(reader, new InputSource(XMLFileName));

       Result result = new StreamResult(OutputFileName);
       Source style = new StreamSource(StyleFileName);

       TransformerFactory transFactory = 
       TransformerFactory.newInstance();
       Transformer trans = transFactory.newTransformer(style);

       trans.transform(source, result);
         
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    }         

  }
}

Notice that everything stays the same except the creation of the Source object. The purpose of the XMLReader object in any SAX application is to generate events based on the document's content and send them to another application. In most cases, that application is a ContentHandler object. But in this case, the XMLReader sends its events to the Transformer through the SAXSource object that's created with it as a foundation.


A SAX stream as the Result object

Usually, SAX and XSL transformations interact because the input for a SAX application is data that is being manipulated through XSLT before processing by the SAX ContentHandler. To accomplish this, you need to create a transformation that outputs to the SAX stream.

Actually, you're not really outputting to a SAX stream, but replacing it. In a normal SAX application, the XMLReader produces events, such as startElement or endDocument, that are consumed by the ContentHandler object. When you use a SAXResult in a transformation, what you're really doing is replacing the XMLReader and feeding events directly to a ContentHandler:


Listing 3. A SAX stream as output
                

...
import javax.xml.transform.sax.SAXResult;
import org.xml.sax.ContentHandler;

public class TransformSAX extends Object {
  public static void main (String args[]) throws Exception
  {
    try {
       String XMLFileName = "mySource.xml";
       String StyleFileName = "myStyle.xsl";
         
       String parserClass = 
             "org.apache.crimson.parser.XMLReaderImpl";
       XMLReader reader = 
             XMLReaderFactory.createXMLReader(parserClass);
       Source source = 
             new SAXSource(reader, new InputSource(XMLFileName));

         ContentHandler theHandler = new MyHandler();
         Result result = new SAXResult(theHandler);
                  
       Source style = new StreamSource(StyleFileName);

       TransformerFactory transFactory = 
             TransformerFactory.newInstance();
       Transformer trans = transFactory.newTransformer(style);

       trans.transform(source, result);
         
    } catch (SAXException e) {
        System.out.println(e.getMessage());
    }         

  }
}

Here, as before, everything stays the same except for the creation of the Result object -- and the ultimate results. The SAXResult takes the ContentHandler object of your choice as the argument, and when the Transformer actually performs the transformation, that's where the results go, and not to the original file. Notice that you don't even have the results file defined any more.

Instead, the theHandler object receives the events as though they'd come from an XMLReader directly, and acts on them just as it would in a traditional SAX application.


Summary

This tip demonstrates a simple application that both consumes and produces a stream of SAX events, allowing you to integrate XSL transformations into your applications directly, without the hassle of having to create intermediate files or other objects to hold your data.



Download

DescriptionNameSizeDownload method
Source files for this tipx-tiptrax/SAXTransSource.zip1.16 KB HTTP

Information about download methods


Resources

About the author

Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of Site Dynamics Interactive Communications in Clearwater, FL, USA, and is the author of three books on Web development, including Java and XML From Scratch (Que) and the upcoming Primer Plus XML Programming (Sams). He loves to hear from readers and can be reached at nicholas@nicholaschase.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=12124
ArticleTitle=Tip: XSL transformations to and from a SAX stream
publish-date=07012002
author1-email=nicholas@nicholaschase.com
author1-email-cc=