SAXParserFactory Example

16 April 2008

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.

import java.io.OutputStreamWriter;
import java.io.Writer;
 
// JAXP
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
            factory.setValidating(true);
            factory.setNamespaceAware(false);
            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) {
            e.printStackTrace();
        }
    }
}
 
class MyHandler extends DefaultHandler {
    // SAX callback implementations from ContentHandler, ErrorHandler, etc.
}

del.icio.us:SAXParserFactory Example  digg:SAXParserFactory Example  spurl:SAXParserFactory Example  wists:SAXParserFactory Example  simpy:SAXParserFactory Example  newsvine:SAXParserFactory Example  blinklist:SAXParserFactory Example  furl:SAXParserFactory Example  reddit:SAXParserFactory Example  fark:SAXParserFactory Example  blogmarks:SAXParserFactory Example  Y!:SAXParserFactory Example  smarking:SAXParserFactory Example  magnolia:SAXParserFactory Example  segnalo:SAXParserFactory Example  gifttagging:SAXParserFactory Example

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: SAXParserFactory Example

Leave a Reply