Using XSLT with DOM

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


Using the DOM APIs, an XML document can be read into a DOM tree. After a DOM is created, you can manipulate the DOM, such as adding or deleting element nodes and so on. After the changes are made in the DOM, you might want to save it back as an XML file. The XSLT APIs help you generate XML out of a DOM.

To understand how to use XSLT with DOM, create an application called MyDOMTransformer that does the following:

  • Reads an XML file into a DOM. Use the CarParts.xml file that was created in the earlier chapters as the sample XML file.

  • Adds a new engine element node to the DOM.

  • Removes the carstereo element node from the DOM.

  • Using the XSLT APIs, generates the modified DOM as XML.

Sequence of Steps in Using XSLT with DOM

The following sequence of steps needs to be followed to use XSLT with DOM:

  1. Import the JAXP and other packages and classes.

  2. Create the DOM application.

  3. Get an instance of the TransformerFactory class.

  4. Get an instance of the Transformer. This can be obtained using the newTransformer() method of the TransformerFactory class.

  5. Provide an error-handling mechanism for XSLT and other exceptions.

  6. Ensure that the DTD information is preserved in the resultant XML.

  7. Transform the modified DOM to XML.

Importing the JAXP Classes

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

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 java.io.File; import java.io.IOException; import org.w3c.dom.*; import org.xml.sax.ErrorHandler; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.OutputKeys; 

DocumentBuilder, DocumentBuilderFactory, FactoryConfigurationError, and ParserConfigurationException are the JAXP classes that enable an application to get a DOM parser and handle related errors. The next two in the list are the SAXException and SAXParseException. These are required to handle exceptions raised during the document parse. Next, the File and IOException classes are imported to handle the errors related to reading the XML file and related I/O tasks.

The classes in the org.w3c.dom package provide the necessary APIs for working with the DOM. The ErrorHandler class enables the application to provide an error-handling mechanism for the validation errors and warnings.

Of interest to us are the javax.xml.transform.* classes. These classes enable an application to create a transformer and handle related exceptions. The javax.xml.transform.dom.DOMSource class is imported to provide a DOM as a source tree for the transform. Since the transformed XML is to be displayed on the screen, the javax.xml.transform.stream.StreamResult is imported to store the result of the transformation as a stream.

Finally, javax.xml.transform.OutputKeys is imported to ensure that the DTD information is preserved.

The next step is to create the DOM application.

Creating the DOM Application

Create the MyDOMTransformer application to create a DOM tree from the CarParts.xml file. Next, ensure that the DOM is modified by adding a new engine element and by removing the carstereo element. To do so, add the lines of code in Listing 6.1.

Listing 6.1 The MyDOMTransformer Application
public class MyDOMTransformer {    static Document document;    public static void main(String argv[])    {         DocumentBuilderFactory factory =       DocumentBuilderFactory.newInstance();         factory.setValidating(true);       try {           DocumentBuilder builder = factory.newDocumentBuilder();           builder.setErrorHandler(new MyErrorHandler());           System.out.println("\n----------------- Creating the DOM from the CarParts.xml  graphics/ccc.gifFile ---------- \n");                     document = builder.parse( new File("CarParts.xml") );           System.out.println("\n----------------- DOM Created from the CarParts.xml file  graphics/ccc.gif---------- \n");          //manipulating the dom to create a new engine  element and remove the carstereo  graphics/ccc.gifelement             NodeList list = document.getElementsByTagName("engines");             Element newNode = document.createElement("engine");             ((Element)list.item(0)).appendChild(newNode);             newNode.setAttribute("id","ID7232");             newNode.setAttribute("type","Alfa-D");             newNode.setAttribute("capacity","1500CC");             newNode.setAttribute("price","USD1000");             newNode.appendChild(document.createTextNode("Engine 3"));             newNode.appendChild(document.createTextNode(""));             newNode.appendChild(document.createTextNode(" contd"));             list = document.getElementsByTagName("carstereos");             Node tobeRmvd = list.item(0).getFirstChild().getNextSibling();             ((Element)list.item(0)).removeChild(tobeRmvd);             document.getDocumentElement().normalize();       } catch (SAXParseException saxException) {                           /* If there are errors in XML data are trapped and location is  graphics/ccc.gifdisplayed*/                           System.out.println("\n\nError in CarParts.xml at line: graphics/ccc.gif"+saxException.getLineNumber()+"("+ saxException.getColumnNumber()+")\n");                           System.out.println(saxException.toString());                       }               catch (SAXException saxEx) {                                   /* If there are errors in XML data, the detailed  graphics/ccc.gifmessage of the exception 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();               }          }// End of main          static class MyErrorHandler implements ErrorHandler              {                  public void fatalError(SAXParseException saxException)                  {                    System.out.println("Fatal Error occurred "+ saxException);                  }                  public void error(SAXParseException saxException)                  {                      System.out.println("Error occurred "+ saxException);                  }                  public void warning(SAXParseException saxException)                  {                      System.out.println("warning occurred "+ saxException);                  }           }       } // End of MyDOMHandler 

The MyDOMTransformer application is now set up to create a DOM from the CarParts.xml file and to modify the DOM. It also implements an error handler to handle the errors that might arise during the parsing process.

Setting Up the XSLT Transformer

The next step is to set up the XSLT Transformer. Setting up the XSLT Transformer consists of creating an instance of the TransformerFactory class and then creating a Transformer instance from the instance of the TransformerFactory class.

To set up the XSLT transformer, add the lines of code listed in bold:

public static void main(String argv[])    {     ........ System.out.println("\n----------------- DOM Created from the CarParts. xml file  graphics/ccc.gif---------- \n");           //Create a transformer           TransformerFactory tnsfctry = TransformerFactory.newInstance();           Transformer transformer = tnsfctry.newTransformer();           //manipulating the dom to create a new engine element and remove the carstereo  graphics/ccc.gifelement             NodeList list = document.getElementsByTagName("engines"); ........................ }//end of main 

Handling Errors

Next you will update the application to handle transformer errors. There are two types of errors that can be thrown: TransformerConfigurationException and TransformerException. A TransformerConfiguration exception is thrown by the factory class when there is a serious configuration error, such as when the transformation factory class specified with the javax.xml.transform.TransformerFactory system property cannot be found or instantiated.

TransformerExceptions are thrown by the transformer object if there are errors during the transformation process. To provide error handling for these two exceptions, add the lines of code listed in bold:

} catch (SAXParseException saxException) {                           /* If there are errors in XML data are trapped and location is  graphics/ccc.gifdisplayed*/                           System.out.println("\n\nError in CarParts.xml at line: graphics/ccc.gif"+saxException.getLineNumber()+"("+saxException. getColumnNumber()+")\n");                           System.out.println(saxException.toString());                       }               catch (SAXException saxEx) {                                   /* If there are errors in XML data, the  detailed  graphics/ccc.gifmessage of the exception 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());         }          }// End of main 

You've now ensured that in case of an exception, the application will display the error message and the location where the error occurred.

Next, you will ensure that the DTD information is preserved in the transformed XML. To do that, add the lines of code listed in bold:

document.getDocumentElement().normalize();          String docTypeID = document.getDoctype().getSystemId();          transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docTypeID);       } catch (SAXParseException saxException) { 

First, the system ID of the DTD defined in the CarParts.xml file is retrieved and stored in a string. The system ID is then used as the value in the DOCTYPE_SYSTEM property of the OutputKeys class. This property ensures that the resulting XML will always have a document type declaration immediately before the first element. The value of the DTD will be picked up from the value specified for the DOCTYPE_SYSTEM property.

Generating the Transformed XML

Finally, you need to update the application 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 our case, the source will be the DOM 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:

transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docTypeID);             DOMSource source = new DOMSource(document);             StreamResult result = new StreamResult(System.out);             transformer.transform(source,result);       } catch (SAXParseException saxException) { 

The application is now ready to transform a DOM source into XML.

NOTE

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


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

Listing 6.2 Output of MyDOMTransfer
----------------- DOM Created from the CarParts.xml file ---------- <?xml version="1.0" encoding="UTF-8"?> <!--  XML file that describes car parts --> <!--  DTD for the XML file that descibes car  graphics/ccc.gifparts --> <!DOCTYPE carparts SYSTEM "CarParts.dtd"> <carparts>     <?supplierformat format="X13" version="3.2"?>     <supplier URL="http://carpartsheaven.com" name="Heaven Car Parts (TM)">     Heaven Car Parts (TM)     </supplier>     <engines>         <engine capacity="2500"  price="3500" type="Alpha37">             Engine 1         </engine>         <engine capacity="2500"  price="4500" type="Beta37">                     Engine 2         </engine>    <engine capacity="1500CC"  price="USD1000" type="Alfa-D"> Engine 3 contd</ graphics/ccc.gifengine></engines>     <carbodies>         <carbody color="blue"  type="Tallboy">             Car Body 1         </carbody>     </carbodies>     <wheels>         <wheel  price="120" type="X3527">             Wheel Set 1         </wheel>     </wheels>     <carstereos>     </carstereos>     <forCDATA><![CDATA[Special Text: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>  graphics/ccc.gif>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SAMS Publishing is the &best&  graphics/ccc.gif<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>..]]> </forCDATA> </carparts> 

Notice that in the output XML, the new engine element has been added and the carstereo element has been removed. Also, the DTD information has been preserved in the transformed XML.


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

 
 


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