The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.xml.parsers  [8 examples] > SAX  [1 examples]

e517. The Quintessential Program to Parse an XML File Using SAX

    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    
    public class BasicSax {
        public static void main(String[] args) {
            // Create a handler to handle the SAX events generated during parsing
            DefaultHandler handler = new MyHandler();
    
            // Parse the file using the handler
            parseXmlFile("infilename.xml", handler, false);
        }
    
        // DefaultHandler contain no-op implementations for all SAX events.
        // This class should override methods to capture the events of interest.
        static class MyHandler extends DefaultHandler {
        }
    
        // Parses an XML file using a SAX parser.
        // If validating is true, the contents is validated against the DTD
        // specified in the file.
        public static void parseXmlFile(String filename, DefaultHandler handler, boolean validating) {
            try {
                // Create a builder factory
                SAXParserFactory factory = SAXParserFactory.newInstance();
                factory.setValidating(validating);
    
                // Create the builder and parse the file
                factory.newSAXParser().parse(new File(filename), handler);
            } catch (SAXException e) {
                // A parsing error occurred; the xml input is not valid
            } catch (ParserConfigurationException e) {
            } catch (IOException e) {
            }
        }
    }

 Related Examples

See also: DOM    DOM Parsing Options   


© 2002 Addison-Wesley.