// Event
Based XML Parsing – SAX
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;
}
}
/**
Count the number 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;
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu