SAX – Example 2

Example program to demonstrate SAX Parsing

// Program 2 – Display the content of Link elements

// 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 PrintElementsHelper extends DefaultHandler

{

boolean inLink = false;

StringBuffer charData;

PrintElementsHelper()

{

super();

}

public void startElement(String namespaceURI, String localName,    String qName,

Attributes attr) throws SAXException

{

if (qName.equals(“link”))

{

inLink = true;

charData = new StringBuffer();

}

return;

}

public void characters(char chars[], int firstChar, int nChars)     throws SAXException

{

if (inLink)

{

charData.append(chars, firstChar, nChars);

}

return;

}

public void endElement(String namespaceURI, String localName, String qName) throws

SAXException

{

if (qName.equals(“link”))

{

System.out.println(“Link data: ” + charData.toString());

inLink = false;

}

return;

}

}

/** Main Program – Display the contents of link elements in an XML document */

class SAXPrintElements

{

/** 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 PrintElementsHelper());

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;

}

}