The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.xml.transform.sax  [1 examples]

e523. Generating SAX Parsing Events by Traversing a DOM Document

If you have developed a set of handlers for SAX events, it is possible to use these handlers on a source other than a file. This example demonstrates how to use the handlers on a DOM document.
    // Obtain a DOM document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    // Prepare the DOM source
    Source source = new DOMSource(doc);
    
    // Set the systemId of the source. This call is not strictly necessary
    URI uri = new File("infilename.xml").toURI();
    source.setSystemId(uri.toString());
    
    // Create a handler to handle the SAX events
    DefaultHandler handler = new MyHandler();
    
    try {
        // Prepare the result
        SAXResult result = new SAXResult(handler);
    
        // Create a transformer
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
    
        // Traverse the DOM tree
        xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
    
    // DefaultHandler contain no-op implementations for all SAX events.
    // This class should override methods to capture the events of interest.
    class MyHandler extends DefaultHandler {
    }

© 2002 Addison-Wesley.