View RSS Feed

My Java Tips

JAXP exposes SAX

Rate this Entry
by , 10-31-2011 at 05:04 PM (681 Views)
Many of you must be using JAXP API, the Java API for XML Processing for XML processing.



The code below shows a fragment that uses JAXP for some SAX parsing.

Java Code:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
parser.parse(new File(args[0]), new MyHandler());
This surely looks similar to SAX parsing, though class names are different.

One can use JAXP constructs and get closer to SAX. JAXP SAXParser class provides a method called getXMLReader()
that returns the underlying SAX XMLReader implementation:


Java Code:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
One can use XMLReader instance as we do with simple SAX application which of course includes setting an error handler.


Using JAXP for DOM parsing provides an even easier DOM-to-SAX layering of APIs. Shown below is a code fragment demonstrating the normal DOM parsing procedure.

Java Code:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();

factory.setValidating(true);
factory.setNamespaceAware(false);

DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(args[0]));
Its is clearly DOM-based parsing, and it's pretty easy to return to SAX. Remember that if you use JAXP, you have got SAX classes already. So if you use JAXP, don't even worry about converting from DOM to SAX. Just rewrite a few lines of code to use SAXParser instead of DOMBuilder and you're ready to add SAX-specific error handling.

Submit "JAXP exposes SAX" to Facebook Submit "JAXP exposes SAX" to Digg Submit "JAXP exposes SAX" to del.icio.us Submit "JAXP exposes SAX" to StumbleUpon Submit "JAXP exposes SAX" to Google

Tags: None Add / Edit Tags
Categories
XML

Comments