View RSS Feed

My Java Tips

SAXParserFactory Example

Rate this Entry
by , 11-28-2011 at 06:17 PM (2226 Views)
To change the parser implementations, JAXP provides a class called SAXParserFactory. I will present an example that will show how to use this class.

First thing is to create an instance of SAXParserFactory. After creating the new instance, we have to get he SAX-capable parser. For thos, factory provides a method. Good thing is that the JAXP implementation takes care of the vendor-dependent code and thus keeps the code clean. This factory has some other nice features, as well. Do explore those.

Java Code:

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;

// SAX
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TestSAXParsing {
    public static void main(String[] args) {
        try {
            if (args.length != 1) {
                System.err.println ("Usage: java TestSAXParsing [filename]");
                System.exit (1);
            // Get SAX Parser Factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // Turn on validation, and turn off namespaces
            SAXParser parser = factory.newSAXParser();
            parser.parse(new File(args[0]), new MyHandler());
        } catch (ParserConfigurationException e) {
            System.out.println("The underlying parser does not support " +
                               " the requested features.");
        } catch (FactoryConfigurationError e) {
            System.out.println("Error occurred obtaining SAX Parser Factory.");
        } catch (Exception e) {

class MyHandler extends DefaultHandler {
    // SAX callback implementations from ContentHandler, ErrorHandler, etc.

Submit "SAXParserFactory Example" to Facebook Submit "SAXParserFactory Example" to Digg Submit "SAXParserFactory Example" to Submit "SAXParserFactory Example" to StumbleUpon Submit "SAXParserFactory Example" to Google

Java EE