// JAXP classes import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; // SAX classes import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** Count the number of link elements in an XML document */ class SAXCountLinks { /** Source for RSS feed */ //static String FEED_URL = "http://today.java.net/rss/21.rss"; /** Initialize XMLReader and set up event handlers */ static public void main(String args[]) { try { String FEED_URL = args[0]; // JAXP-style initialization of SAX parser SAXParserFactory saxFactory = SAXParserFactory.newInstance(); XMLReader parser = saxFactory.newSAXParser().getXMLReader(); // SAX-style processing of RSS document at FEED_URL parser.setContentHandler(new CountElementsHelper()); parser.parse(FEED_URL); } catch (Exception e) { e.printStackTrace(); } return; } /** Helper class containing SAX event handler methods */ private static class CountElementsHelper extends DefaultHandler { /** Number of 'p' elements seen so far */ int numElements; /** Constructor (allows for superclass initialization) */ CountElementsHelper() { 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 atts) throws SAXException { if (qName.equals("link")) { numElements++; } return; } /** Done with document; output final count */ public void endDocument() throws SAXException { System.out.println("Input document has " + numElements + " 'link' elements."); return; } } }