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 // 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 { }

Comments

11 Mar 2010 - 4:02pm by Anonymous (not verified)

Thank you!!! You don't know how much searching it took me to find this!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.