// 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; import org.xml.sax.InputSource; import java.io.FileReader; /** Print the content of the link elements in an XML document */ class SAXPrintLinks { /** Source for RSS feed */ // static String FEED_FILE_NAME = "ExampleContentFeed.xml"; /** Initialize XMLReader and set up event handlers */ static public void main(String args[]) { try { String FEED_FILE_NAME= args[0]; // JAXP-style initialization of SAX parser SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setValidating(false); // make default explicit saxFactory.setNamespaceAware(false); // make default explicit XMLReader parser = saxFactory.newSAXParser().getXMLReader(); parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true); // make default explicit // SAX-style processing of RSS document at FEED_FILE_NAME parser.setContentHandler(new PrintElementsHelper()); parser.parse(new InputSource(new FileReader(FEED_FILE_NAME))); } catch (Exception e) { e.printStackTrace(); } return; } /** Helper class containing SAX event handler methods */ private static class PrintElementsHelper extends DefaultHandler { /** Whether or not we are in a link element */ boolean inLink = false; /** Character data collected for the current link element */ StringBuffer charData; /** Constructor (allows for superclass initialization) */ PrintElementsHelper() { super(); } /** Process the start of an element */ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (qName.equals("link")) { inLink = true; charData = new StringBuffer(); } return; } /** Process character data */ public void characters(char chars[], int firstChar, int nChars) throws SAXException { if (inLink) { charData.append(chars, firstChar, nChars); } return; } /** Process the end of an element. If link, output collected character data. */ 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; } } }