SAX – Example 1

Example program to demonstrate SAX Parsing

 

// Program 1 – To count the number of link elements in the input file

// Link to sample input file – rss.xml 

import javax.xml.parsers.*;

import org.xml.sax.*;

import org.xml.sax.helpers.DefaultHandler;

/** Helper class containing SAX event handler methods */

class CountElements extends DefaultHandler

{

int numElements;

/** Constructor (allows for superclass initialization) */

CountElements()

{

super();

}

/** Perform initialization for this instance */

public void startDocument() throws SAXException

{

numElements = 0;

return;

}

/** Process the start of an element */

public void startElement(String namespaceURI, String localName, String qName, Attributes attr) throws SAXException

{

if (qName.equals(“link”))

{

numElements++;

}

return;

}

/** Output final count */

public void endDocument() throws SAXException

{

System.out.println(“Input document has ” + numElements + ” ‘link’ elements.”);

return;

}

}

/** Main Program – Count the number of link elements in an XML document */

class SAXCountLinks

{

/** Source document */

static String FEED_URL = “rss.xml”;

static public void main(String args[])

{

try

{

SAXParserFactory saxFactory = SAXParserFactory.newInstance();

XMLReader parser = saxFactory.newSAXParser().getXMLReader();

parser.setContentHandler(new CountElements());

parser.parse(FEED_URL);

}

catch (SAXParseException spe)

{

System.err.println(“Parse error at line ” + spe.getLineNumber() + “,

character ” + spe.getColumnNumber());

if (spe.getException() != null)

{

spe.getException().printStackTrace();

}

else

{

spe.printStackTrace();

}

}

catch (SAXException se)

{

if (se.getException() != null)

{

se.getException().printStackTrace();

}

else

{

se.printStackTrace();

}

}

catch (Exception e)

{

e.printStackTrace();

}

return;

}

}