Using XSLT with SAX

printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    

Java APIs for XML Kick Start
By Aoyon Chowdhury, Parag Choudhary

Table of Contents
Chapter 6.  XSLT and XPath


Similar to using DOM-specific XSLT transforms, there are SAX-specific XSLT transforms available through the javax.xml.transform.sax package.

To understand how to use the XSLT transforms with SAX, create an application called MySAXTransformer.java. This is a simple application that reads an XML file and provides it as a SAX input source to create the SAXSource object.

The application will then transform this XML to display the resultant XML in the screen. Although this is a very simple example, in which the input XML file is read-out as is, it will give you an idea of how to use SAX-specific XSLT APIs.

Using SAX-Specific XSLT APIs

The following sequence of steps needs to be followed to use SAX-specific XSLT APIs:

  1. Import the JAXP and other packages and classes.

  2. Create the InputSource object.

  3. Get an instance of the TransformerFactory class.

  4. Get an instance of the Transformer.

  5. Provide an error-handling mechanism for XSLT-related exceptions.

  6. Transform the XML.

Importing the JAXP and Other Classes

Let's begin writing the application MySAXTransformer.java. MySAXTransformer is a simple application that converts the CarParts.xml file as a SAX input source to create the SAXSource object, transforms the XML, and handles the errors, if any, that are generated during the transformation process.

The first step is to import the classes necessary for the application to access the JAXP and XSLT APIs. In the MySAXTransformer.java file, add the following lines:

import org.xml.sax.InputSource; import java.io.*; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; 

The org.xml.sax.InputSource class enables the encapsulation of the entire XML document into a single object. As you will see in the application, the CarParts.xml file will be encapsulated in the InputSource object, and then this object is used to create the SAXSource object. The InputSource object is used to determine how to read XML input. If there is a character stream available, it will be read directly. If there is no input stream, a byte stream may be used. If neither a character stream nor a byte stream is available, an attempt to open a URI connection to the resource identified by the system identifier is performed.

Next, the classes in the io package are imported to handle the errors related to reading the XML file and related I/O tasks. The javax.xml.transform.* classes are imported to enable an application to create a transformer and handle related exceptions.

The javax.xml.transform.dom.SAXSource class is imported to provide a SAXSource for the transform. Since the transformed XML is to be displayed on the screen, the javax.xml.transform.stream.StreamResult is imported to provide an output stream for the result.

Creating the InputSource Object

Next you'll create the InputSource object. The InputSource object is created from the CarParts.xml file. This object is then used to create the SAXSource object. Add the following lines of code to provide the class declaration and the main() method for the MySAXTransform application, as well as to create the InputSource object:

public class MySAXTransformer{ static public void main(String[] args) {         File f = new File("CarParts.xml");         FileReader fr = new FileReader(f);         BufferedReader br = new BufferedReader(fr);         InputSource inputSource = new InputSource(br); }//end of main } 

Setting Up the XSLT Transformer

Setting up the XSLT Transformer is a two-step process: First, create an instance of the TransformerFactory class, and then create a Transformer instance from that instance of the TransformerFactory class. Both of these steps are taken care of by adding the lines in bold listed here:

static public void main(String[] args) {         File f = new File("CarParts.xml");         FileReader fr = new FileReader(f);         BufferedReader br = new BufferedReader(fr);         InputSource inputSource = new InputSource(br);         TransformerFactory tnsfctry = TransformerFactory.newInstance();         Transformer transformer = tnsfctry.newTransformer();  } //end of main } 

Handling Errors

The next step is to update the application to handle errors. The application can throw three types of errors: IOException, TransformerConfigurationException, and TransformerException. To provide error handling for these two exceptions, add the lines of code listed in bold:

static public void main(String[] args) { try{         File f = new File("CarParts.xml");         FileReader fr = new FileReader(f);         BufferedReader br = new BufferedReader(fr);         InputSource inputSource = new InputSource(br);         TransformerFactory tnsfctry = TransformerFactory.newInstance();         Transformer transformer = tnsfctry.newTransformer();         }         catch (IOException ioe) {         // I/O error            ioe.printStackTrace();         }         catch (TransformerConfigurationException tcex)         {             System.out.println(tcex.getMessageAndLocation());         }         catch (TransformerException te)         {             System.out.println(te.getMessageAndLocation());         }  }// end of main 

Generating the Transformed XML

The final step is adding the code to generate the transformed XML. Generating the transformed XML is a simple process of creating the source and the result, and then calling the transform() method of the transformer object to transform the XML. In this case, the source will be the SAX source, and the result will be a stream, because the XML is to be shown on the display.

To generate the transformed XML, add the lines of code listed in bold:

static public void main(String[] args) {         try{         File f = new File("CarParts.xml");         FileReader fr = new FileReader(f);         BufferedReader br = new BufferedReader(fr);         InputSource inputSource = new InputSource(br);         TransformerFactory tnsfctry = TransformerFactory.newInstance();         Transformer transformer = tnsfctry.newTransformer();         SAXSource source = new SAXSource(inputSource);         StreamResult result = new StreamResult(System.out);         transformer.transform(source,result);         }         catch (IOException ioe) {         // I/O error            ioe.printStackTrace();         }         catch (TransformerConfigurationException tcex)         {             System.out.println(tcex.getMessageAndLocation());         }         catch (TransformerException te)         {             System.out.println(te.getMessageAndLocation());         }  }// end of main 

The application is now ready to transform a SAX source into an XML document.

NOTE

The code discussed here is available in the example0602 folder. This folder also contains the sample CarParts.xml file.


Compile and run the application. The output should be similar to Listing 6.3.

Listing 6.3 Output of MySAXTransformer
<?xml version="1.0" encoding="UTF-8"?> <!--  XML file that describes car parts --> <!DOCTYPE carparts SYSTEM "CarParts.dtd" [ <!ENTITY companyname "Heaven Car Parts (TM)"> <!ENTITY companyweb "http://carpartsheaven.com"> <!ELEMENT carparts (supplier,engines,carbodies,wheels,carstereos,forCDATA)> <!ELEMENT engines (engine+)> <!ELEMENT carbodies (carbody+)> <!ELEMENT wheels (wheel+)> <!ELEMENT carstereos (carstereo+)> <!ELEMENT forCDATA (CDATA)> <!ELEMENT supplier (#PCDATA)> <!ATTLIST supplier name CDATA #REQUIRED> URL CDATA #REQUIRED> <!ELEMENT engine (#PCDATA)*> <!ATTLIST engine id CDATA #REQUIRED> type CDATA #REQUIRED> capacity (1000|2000|2500) #REQUIRED> price CDATA #IMPLIED> text CDATA #IMPLIED> <!ELEMENT carbody (#PCDATA)*> <!ATTLIST carbody id CDATA #REQUIRED> type CDATA #REQUIRED> color CDATA #REQUIRED> <!ELEMENT wheel (#PCDATA)*> <!ATTLIST wheel id CDATA #REQUIRED> type CDATA #REQUIRED> price CDATA #IMPLIED> size (X|Y|Z) #IMPLIED> <!ELEMENT carstereo (#PCDATA)*> <!ATTLIST carstereo id CDATA #REQUIRED> manufacturer CDATA #REQUIRED> model CDATA #REQUIRED> Price CDATA #REQUIRED> ]> <carparts>     <?supplierformat format="X13" version="3.2"?>     <supplier name="Heaven Car Parts (TM)" URL="http://carpartsheaven.com">     Heaven Car Parts (TM)     </supplier>     <engines>         <engine  type="Alpha37" capacity="2500" price="3500">             Engine 1         </engine>     </engines>     <carbodies>         <carbody  type="Tallboy" color="blue">             Car Body 1         </carbody>     </carbodies>     <wheels>         <wheel  type="X3527" price="120">             Wheel Set 1         </wheel>     </wheels>     <carstereos>         <carstereo  manufacturer="MagicSound" model="T76w" Price="500">             Car Stereo 1         </carstereo>     </carstereos>     <forCDATA><![CDATA[Special Text: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  graphics/ccc.gif>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SAMS Publishing is the &best&  graphics/ccc.gif<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>..]]> </forCDATA> </carparts> 

printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    
Top

[0672324342/ch06lev1sec4]

 
 


JavaT APIs for XML Kick Start
JAX: Java APIs for XML Kick Start
ISBN: 0672324342
EAN: 2147483647
Year: 2002
Pages: 133

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net