Tuesday, August 14, 2007

Generating SAX Parsing Events by Traversing an XML 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.

By DOM Parser:

DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder()
Document doc = builder.parse(new File("inputFile.xml"));

//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("inputFile.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 {
}

By SAX Parser:

SAXParser parser=SAXParserFactory.newInstance().newSAXParser();

//Prepare InputSource
InputSource inputSource=new InputSource(new FileInputStream("inputFile.xml"))

// Create a handler to handle the SAX events
DefaultHandler handler = new MyHandler();


try{

parser.parse(inputSource, handler);

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

No comments: