Sunday, 4 January 2015

Java - SAX (Simple API for XML)


SAX provides a different approach to parsing. Rather than creating a tree form an XML document like DOM.
A SAX parser reads through the file and notifies registered listeners when  certain parsing events occur. The events are as follows..
-         The beginning of a document.
-         Reading a start tag at the beginning of a new element
-         Reading an end tag at the end of an element.
-         Reading text in the body of an element.
-         Reading comments
-         Reaching the end of a document.


How SAX works?

If start tag is found in xml file, sax parser calls startElement() and characters().
If end tag is found in xml file, sax parser calls endElement() and characters().



Difference between SAX and DOM

DOM manages tree based technique to handle xml file.
SAX manages xml file, based on events. Whenever the event is occurred the corresponding method of DefaultHandler will be invoked. So developer must create the sub class of DefaultHandler class.



SAX Parser Program using xmlfile1.xml

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
class SAXParser1
{
public static void main(String args[])
{
try
{
//javax.xml.parsers
SAXParserFactory spf=SAXParserFactory.newInstance();
//javax.xml.parsers
SAXParser parser=spf.newSAXParser();
MyDefaultHandler mdh=new MyDefaultHandler();
FileInputStream is=new FileInputStream("xmlfile1.xml");
parser.parse(is,mdh);
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}

class MyDefaultHandler extends org.xml.sax.helpers.DefaultHandler
{
StringBuffer buffer=new StringBuffer();
public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException
{

System.out.println(qName);
buffer.setLength(0);
}

public void characters(char ch[],int start,int end)
{
buffer.append(ch,start,end);
if (buffer.toString().length()!=0)
{
System.out.print(buffer.toString());
}
}

public void endElement(String uri,String localName,String qName)throws org.xml.sax.SAXException
{

System.out.println(qName);
buffer.setLength(0);
}
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.