XML- SAX Parser using JAXP API

Understanding SAX Parser

At the very first, create an instance of the SAXParserFactory class, which generates an instance of the parser. This parser wraps a SAXReader object. When the parser’s parse() method is invoked, the reader invokes one of the several callback methods (implemented in the application). These callback methods are defined by the interfaces ContentHandler, ErrorHandler, DTDHandler, and EntityResolver.

Brief description of the key SAX APIs:


SAXParserFactory object creates an instance of the parser determined by the system property, using the class javax.xml.parsers.SAXParserFactory.


The SAXParser interface defines several kinds of parse() methods. Generally, XML data source and a DefaultHandler object is passed to the parser. This parser processes the XML file and invokes the appropriate method on the handler object.


The SAXParser wraps a SAXReader (may use


SAXParser’s getXMLReader() and configure it). It is the SAXReader, which carries on the conversation with the SAX event handlers you define.


Not shown in the diagram, a DefaultHandler implements the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver interfaces (with null methods). You override only the ones you’re interested in.


Methods like startDocument, endDocument, startElement, and endElement are invoked when an XML tag is recognized. This interface also defines methods characters and processingInstruction, which are invoked when the parser encounters the text in an XML element or an inline processing instruction, respectively.


Methods error, fatalError, and warning are invoked in response to various parsing errors. The default error handler throws an exception for fatal errors and ignores other errors (including validation errors). To ensure the
correct handling, you’ll need to supply your own error handler to the parser.


Defines methods you will rarely call. Used while processing a DTD to recognize and act on declarations for an unparsed entity.


The resolveEntity method is invoked when the parser needs to identify the data referenced by a URI. .

Lets see an example of parsing an XML document using Java SAX Parser. In this section, we are going to develop a simple Java program named that first determines whether a XML document is wellformed
or not then retrieves data from XML

Feb  2008 | Java Jazz Up |27
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 ,

Download PDF