Thursday, January 29, 2009

Learning JAXP

When i referred to this link http://www.ibm.com/developerworks/java/library/x-jaxp it pointed out that it is good to have knowledge on SAX(Simple API for XML) and DOM.

So started with SAX. It is an open source project with no license whatsoever. I started with the "Quickstart" page(http://www.saxproject.org/quickstart.html).

It details a simple example of how to use a SAX parser and what you can do with it.
SAX is an event based XML parser. We would extend the org.xml.sax.helpers.DefaultHandler. Then we would have to create a SAX Driver and attach this handler to it.This provides callback to the events like startDocument(when the SAX Driver finds the beginning of a document) or startElement(when SAX driver starts to parse an element).

I just expanded the example given in the site to check if the XML supplied has all the tags and that they are properly ended or not.
For this i used the startTag() and endTag() callback method.

import java.io.FileReader;
import java.io.IOException;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.util.ArrayList;

public class SaxApp extends DefaultHandler{
public SaxApp(){
super();
}
ArrayList arrList = new ArrayList();
boolean error = false;
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("End Document");
if(error)
System.out.println("There is error in the document..");
else
System.out.println("There is no error in the document..");
}

public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
System.out.println("Start Document");
}

public void startElement (String uri, String name,
String qName, Attributes atts)
{
if ("".equals (uri)){
System.out.println("Start element: " + qName);
arrList.add(qName);
}
else
System.out.println("Start element: {" + uri + "}" + name);
}

public void endElement (String uri, String name, String qName)
{
if ("".equals (uri)){
System.out.println("End element: " + qName);
String last =(String)arrList.get(arrList.size()-1);
System.out.println("Last element is :"+last);
if(last.equals(qName)){
arrList.remove(arrList.size()-1);
}else
error = true;
}
else
System.out.println("End element: {" + uri + "}" + name);
}


public static void main(String args[]){
try {
SaxApp app = new SaxApp();
XMLReader myReader = XMLReaderFactory.createXMLReader();
FileReader freader = new FileReader("C:\\error-log-0.xml");

myReader.setContentHandler(app);
myReader.setErrorHandler(app);

myReader.parse(new InputSource(freader));
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

No comments: