Web Technologies
|
|
SAX
SAX
1. Introduction:
SAX stands for Simple API for XML. API stands for Application Programming Interface.
An API is a source code provided by an operating system or a library in order to
handle a requestWindows Shell is an API; JDBC is an API.
Since JDBC plys the role of the bridge between Java and relational database,
SAX plays the role between Java and XML. SAX is generally an implemented interface
parser like the DOM (Document Object Model) parsing interface.
DOM interface parses an entire XML document and constructs an in-memory representation
of the document, known then ny DocumentBuilder.The package javax.xml.parsers.DocumentBuilder
stems from javax.xml.parsers.DocumentBuilderFactory. The DocumentBuilder creates an
org.w3c.dom.Document instance. This instance is a tree structure that contains
nodes present in the XML Document. Each tree node in the structure implements
org.w3c.dom.Node interface and represents the type of data found in an XML document.
The nodes are element nodes which may have attributes and text nodes representing
the text found between the start and end tags of a document element.
The SAX parser is called the SAXParser. It is created by
javax.xml.parsers.SAXParserFactory. The SAX parser does not create
an in-memory representation of the XML document as DOM does. It is then
faster and uses less memory. The SAX parser informs clients of the
XML document structure by invoking callbacks by invoking methods
on a org.xml.sax.helpers.DefaultHandler instance provided to the parser's
package. The DefaultHandler class implements the ContentHandler, the ErrorHandler,
the DTDHandler, and the EntityResolver interfaces. The
most important methods in the SAX interface are:
- startDocument() and endDocument() methods. They are called at the start and end of an XML document.
- startElement() and endElement() methods. They are called at the start and end of a document element.
- characters() method. It is called between the start and end tags of an XML document element.
To install the related librairy, go to
saxproject.org
and choose download area.
Download and extract sax2.jar.
Place this file in a directory such as:
C:\Program Files\Java\jre1.5.0_14\lib\ext\
Set the classpath as:
CLASSPATH = C:\Program Files\Java\jre1.5.0_14\lib\ext\sax2.jar
2. Example:
Program java:
parseXmlExample.java
to parse an xml document:
atoms.xml.txt
Compile as:
C:\J2EE\SAX>javac parseXmlExample.java
Run as:
C:\J2EE\SAX>java parseXmlExample atoms.xml
The output is:
parsedOutput.txt
|
|
|