Wednesday, December 29, 2010

Sax Parser...A simple way to access xml documents

Sax parser allow us to access a xml document and we can predefine how the program should behave once certain events are occurred in the xml document when the parser parse the xml document from top to bottom.

A simple java code that helps you to access a xml document through your implementation

package sax;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxHelperSanja {

public static void main(String args[]) {



try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {


public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
/*this method is called once the parser meets a start element and you should implement here how your code should behave when a start element is found.The name of the start element is the parameter qName and the attributes of that element is under attributes parameter.*/
}

public void endElement(String uri, String localName,
String qName)
throws SAXException {
/*this method is called once the parser meets an end element and you should implement here how your code should behave when an end element is found.The name of the end element is the parameter qName.*/
}

public void characters(char ch[], int start, int length)
throws SAXException {
/* this method is called once the parser encounters text under an element.*/
}
};

// for specifying the xml document
saxParser.parse("/home/sanjaya/Desktop/a.xml", handler);

} catch (Exception e) {
e.printStackTrace();
}
}
}

there are startDocument() and endDocument() methods that are called when the parser begins the parsing of the xml document and ends the parsing of the document.In the above code I have not included them as I think they are not vital as the once I have mentioned above.Anyway feel free to use these two methods if you really need.

Hey that's the simple sax parsing.enjoy....

No comments:

Post a Comment