This Java tip illustrates a method of an example of a Quintessential program to Parse an XML file Using SAX. The Simple API for XML (SAX)is available with the Java API for XML Processing (JAXP). Along with the Document Object Model, SAX is one of two common ways to write software that accesses XML data. Using SAX with JAXP allows developers to traverse through XML data sequentially, one element at a time, using a delegation event model. Each time elements of the XML structure are encountered, an event is triggered. Developers write event handlers to define custom processing for events they deem important.

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