import java.io.*; // JAXP packages import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * SaxPrint uses the Simple API for XML (SAX) to parse a given XML * document then print its element nodes. * * @author Thornton Rose * @version 1.0 */ public class SaxPrint extends DefaultHandler { /** * Construct an instance of this class. */ public SaxPrint() { } // DefaultHandler methods -------------------------------------------------- /** * Called when the document has started. */ public void startDocument() throws SAXException { System.out.println("BEGIN DOCUMENT"); } /** * Called when the document has ended. */ public void endDocument() throws SAXException { System.out.println(""); System.out.println("END DOCUMENT"); } /** * Called when an element has started. */ public void startElement(String uri, String lName, String qName, Attributes attribs) throws SAXException { // Print node name. System.out.println(""); System.out.println(" BEGIN " + qName); // Print attributes, if any. if (attribs.getLength() > 0) { for (int i = 0; i < attribs.getLength(); i ++) { System.out.println(" ." + attribs.getQName(i) + "=" + attribs.getValue(i)); } } } /** * Called when an element has ended. */ public void endElement(String uri, String lName, String qName) throws SAXException { System.out.println(" END " + qName); } /** * Called when element data has been parsed. */ public void characters(char[] data, int start, int length) throws SAXException { StringBuffer buf = new StringBuffer(length); buf.append(data, start, length); if (buf.toString().trim().length() > 0) { System.out.println(" " + buf); } } //-------------------------------------------------------------------------- /** * Print the given document. */ private void print(File docFile) { try { // Get an instance of parser factory and configure it. SAXParserFactory factory = SAXParserFactory.newInstance(); // Get a parser from the factory. SAXParser parser = factory.newSAXParser(); // Parse the input file and print the elements. parser.parse(docFile, this); } catch(Exception ex) { System.out.println(ex); } } //-------------------------------------------------------------------------- /** * Run the program. */ public static void main(String[] args) { // If not enough args, print usage. if (args.length < 1) { System.out.println("Usage: SaxPrint file"); System.exit(0); } // Get file name from command-line. File docFile = new File(args[0]); // Instantiate class and print. (new SaxPrint()).print(docFile); } }