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....

Tuesday, December 28, 2010

I am back

I was so busy since march as I was fully dealt with completing the gsoc project.And glad to say that I completed it successfully.Soon after I completed the project I wanted to get some vacation and really had a wonderful time in my home having played with my friends until my final year at university begins.Then once again It was and still a tough time as exams are near by.Anyway I think that the time I was away from blogging is too much and thereby I though I must update it.So here I am back again...........