Creating the MyXSLTTransformer Application

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


Creating the MyXSLTTransformer Application

MyXSLTTransformer is a simple Java application that uses a DOM parser to create a Document object from the CarParts.xml file. This Document object is converted to a DOMSource object and used by the Transformer object as the source. Because the output is to be displayed on the screen, System.out is used as the output of the transformation. The Transformer object itself is created by using the CarParts.xsl stylesheet.

First you need to import the necessary packages and classes. To do so, add the following lines of code:

import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.*; 

Next, provide the class declaration and the main() method. To do so, add these lines of code:

public class MyXSLTTransformer {     static Document document;     public static void main (String argv [])     { 

Now the CarParts.xml file needs to be parsed to create a Document object. To do so, add the lines of code shown in bold:

public static void main (String argv [])     {         DocumentBuilderFactory factory =             DocumentBuilderFactory.newInstance();   try {             File stylesheet = new File("CarParts.xsl");             File datafile   = new File("CarParts.xml");             DocumentBuilder builder = factory.newDocumentBuilder();             document = builder.parse(datafile); 

Now you need to create the Transformer object. To do so, add the lines of code shown in bold:

document = builder.parse(datafile); // Use a Transformer for output             TransformerFactory tFactory =                 TransformerFactory.newInstance();             StreamSource stylesource = new StreamSource(stylesheet);             Transformer transformer = tFactory.newTransformer(stylesource); 

The next step is to create the DOMSource and the StreamResult objects. To do so, add the lines of code shown in bold:

Transformer transformer = tFactory.newTransformer(stylesource); DOMSource source = new DOMSource(document);             StreamResult result = new StreamResult(System.out);             transformer.transform(source, result); 

Finally, you will insert the try-catch block to handle the exceptions that may occur add the lines of code shown in bold in Listing 6.4.

Listing 6.4 Adding Exception-Handling Code
try {             File stylesheet = new File("CarParts.xsl");             File datafile   = new File("CarParts.xml");             DocumentBuilder builder = factory.newDocumentBuilder();             document = builder.parse(datafile);             // Use a Transformer for output             TransformerFactory tFactory =                 TransformerFactory.newInstance();             StreamSource stylesource = new StreamSource(stylesheet);             Transformer transformer = tFactory.newTransformer(stylesource);             DOMSource source = new DOMSource(document);             StreamResult result = new StreamResult(System.out);             transformer.transform(source, result);        } catch (SAXParseException saxException) {                                  /* If there are errors in XML data are trapped and  graphics/ccc.giflocation is displayed*/                    System.out.println("\n\nError in CarParts.xml at line:"+saxException.getLineNumber()+"("  graphics/ccc.gif+saxException.getColumnNumber()+")\n");                             System.out.println(saxException.toString());                              }                      catch (SAXException saxEx) {                           /* If there are errors in XML data, the detailed message of the  graphics/ccc.gifexception is displayed*/                                     System.out.println(saxEx.getMessage());                          }                      catch (ParserConfigurationException pce) {                            // Parser with specified options can't be built                            pce.printStackTrace();                          }                      catch (IOException ioe) {                            // I/O error                    ioe.printStackTrace();                      }                    catch (TransformerConfigurationException tcex)                    {                        System.out.println(tcex.getMessageAndLocation());                    }                    catch (TransformerException te)                    {                        System.out.println(te.getMessageAndLocation());                }  } // main } 

The application is now ready to transform CarParts.xml.

NOTE

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


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

Listing 6.5 Output of MyXSLTTransformer Application
<?xml version="1.0" encoding="UTF-8"?> <carcomponents>     <?supplierformat format="X13" version="3.2"?><!--              This XML is checking out the format with our suppliers>          -->     <componentsupplier>     Heaven Car Parts (TM)     </componentsupplier>     <car_engines>         <engine >             Engine 1         </engine>     </car_engines>     <car_bodies>         <body>             Car Body 1         </body>     </car_bodies>     <car_wheels>         <wheel_type>             Wheel Set 1         </wheel_type>     </car_wheels>     <stereos>         <stereo>             Car Stereo 1         </stereo>     </stereos>     <for_CDATA Type="FreeText"><![CDATA[Special Text:  graphics/ccc.gif<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SAMS  graphics/ccc.gifPublishing is the &best& <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>..]]><![CDATA[ ]]></for_CDATA> </carcomponents> 

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/ch06lev1sec8]

 
 


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