// 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 CountElements
extends DefaultHandler
{
/** Number of 'p' elements seen so far */
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("rss"))
{
numElements++;
}
return;
}
/** Done with
document; output final count */
public void endDocument() throws SAXException
{
System.out.println("Input document has " + numElements
+ " 'rss' elements.");
return;
}
}
/**
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;
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu