XML and Java Parsing XML using Java Tutorial

SAX parser is a Event Driven Parser. You provide the callback methods, and the parser invokes them as it reads the XML data. Finally, you can't "back up" to an earlier part of the document, or rearrange it, any more than you can back up a serial data stream or rearrange characters you have read from that stream. The following Packages need to be imported in your Java File to use the SAX parser.
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

public class BooksLibrary extends HandlerBase
Next Let's declare the Main method and also setup the Parser
public static void main (String argv [])
  SAXParserFactory factory = SAXParserFactory.newInstance();
  try {

        out = new OutputStreamWriter (System.out, "UTF8");
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse( new File(XML_FILE_NAME), new BooksLibrary() );

  } catch (Throwable err) {
        err.printStackTrace ();
As seen above first we get a new instance of SAXParserFactory and from this one we create a new Instance of SaxParser. To the Parse Method of SaxParser, we pass two parameters, name of the XML File and the class which implements interface HandlerBase
Currently in our Code, the same JavaFile, BooksLibrary.java implements interface HandlerBase.
    The javax.xml.parsers.SAXParser class is a wrapper that defines a number of convenience methods. It wraps the org.xml.sax.Parser object. If needed, you can obtain that parser using the SAXParser's getParser() method.
The Following Methods needs to be implemented from the DocumentHandlerBase Interface, and Description above each methods explains when this Method is called. These Methods are called automatically while parsing the XML file and when the corresponding data element is reached. Please refer to the attached Java Source File  to see how these methods are implemented. When you run this Program the output will clearly show When a attribute is reached and when a Element is reached and how each of these methods are called.

No comments:

Post a Comment

Please Provide your feedback here