Event oriented XML Parsing: SAX
stands for Simple API for XML
provides a mechanism for reading data from an XML document, SAX parsers operate
on each piece of the XML document sequentially.
It is a
kind of event oriented approach for parsing the xml document.
tree is not viewed as a data structure, but as a stream of events generated by the
of events are:
the start of the document is encountered
the end of the document is
encountered the start tag of an
element is encountered the end tag
of an element is encountered
character data is
a processing instruction is encountered
the XML file from start to end, each event invokes a corresponding callback method that the programmer
1 SAX packages
Describing the main classes needed for parsing org.xml.sax: Describing few
interfaces for parsing
2 SAX classes
Defines the API that wraps an XMLReader implementation class SAXParserFactory
Defines a factory API that enables applications to configure and
SAX based parser to parse XML documents
Receive notification of the logical content of a document. DTDHandler Receive
notification of basic DTD-related events. EntityResolver Basic interface for
Basic interface for SAX error handlers. DefaltHandler Default base class for
SAX event handlers.
3 SAX parser methods
startDocument() and endDocument() – methods called
at the start and end of an XML document.
startElement() and endElement() – methods called at the start and end of
a document element.
characters() – method called with the text contents in between the start
and end tags of an XML document element.
4 Understanding SAX Parser
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.
5 SAX Example :Selecting XML data
Create a XML file
Create a simple XML file as following <?xml
Transforming XML document
process of extracting one info. From one xml doc. and uses that info to create
another xml doc.