Event oriented XML Parsing: SAX
SAX
stands for Simple API for XML
SAX
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.
An XML
tree is not viewed as a data structure, but as a stream of events generated by the
parser.
The kinds
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
encountered
a processing instruction is encountered
Scanning
the XML file from start to end, each event invokes a corresponding callback method that the programmer
writes.
1 SAX packages
javax.xml.parsers:
Describing the main classes needed for parsing org.xml.sax: Describing few
interfaces for parsing
2 SAX classes
SAXParser
Defines the API that wraps an XMLReader implementation class SAXParserFactory
Defines a factory API that enables applications to configure and
obtain a
SAX based parser to parse XML documents
ContentHandler
Receive notification of the logical content of a document. DTDHandler Receive
notification of basic DTD-related events. EntityResolver Basic interface for
resolving entities.
ErrorHandler
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
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.
5 SAX Example :Selecting XML data
Step 1.
Create a XML file
Create a simple XML file as following <?xml
version="1.0"?> <company>
<staff>
<firstname>Ram</firstname>
<salary>100000</salary>
</staff>
<staff>
<firstname>Kumar</firstname>
<salary>200000</salary>
</staff>
</company>
Transforming XML document
It is
process of extracting one info. From one xml doc. and uses that info to create
another xml doc.
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.