import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; public class SAXDemo extends DefaultHandler { String prefix = ".........................."; int depth = 0; StringBuffer textBuffer; public static void main(String argv[]) { if (argv.length != 1) { System.err.println("Usage: cmd filename"); System.exit(1); } // Use an instance of ourselves as the SAX event handler DefaultHandler handler = new SAXDemo(); // Use the default (non-validating) parser SAXParserFactory factory = SAXParserFactory.newInstance(); try { // Parse the input SAXParser saxParser = factory.newSAXParser(); saxParser.parse( new File(argv[0]), handler ); } catch (Throwable t) { t.printStackTrace(); } } public void startElement( String namespaceURI, String sName, // simple name String qName, // qualified name Attributes attrs) throws SAXException { depth++; System.out.print(prefix.substring(0, depth)); System.out.println(qName + " node detected"); // System.out.println(sName + " = sname"); int n = attrs.getLength(); for(int i = 0; i < n; i++) { depth++; System.out.print(prefix.substring(0, depth)); System.out.println("attribute node: (" + attrs.getQName(i) + ", " + attrs.getValue(i) + ")"); depth--; } } public void endElement( String namespaceURI, String sName, // simple name String qName // qualified name ) throws SAXException { if (textBuffer != null) { String s = ""+textBuffer; s = s.trim(); if (!s.equals("")) { depth++; System.out.print(prefix.substring(0, depth)); System.out.println("text node: " + s); depth--; } textBuffer = null; } depth--; //System.out.println("==================="); } public void characters(char buf[], int offset, int len) throws SAXException { String s = new String(buf, offset, len); if (textBuffer == null) { textBuffer = new StringBuffer(s); } else { textBuffer.append(s); } } }