import org.xml.sax.*; import org.xml.sax.helpers.*; public class SaxBeispiel{ public static void main (String args[]) throws Exception { Parser parser = ParserFactory.makeParser("org.apache.xerces.parsers.SAXParser"); DocumentHandler docHandler = new MeinDocHandler(); parser.setDocumentHandler(docHandler); ErrorHandler errorHandler = new MeinErrorHandler(); parser.setErrorHandler(errorHandler); for (int i = 0; i < args.length; i++) { parser.parse(args[i]); } } } class MeinDocHandler implements DocumentHandler { private Locator locator = null; public void startDocument () { System.out.println("Parsen beginnt"); } public void endDocument () { System.out.println("Parsen beendet"); } public void startElement (String name, AttributeList attrs) { int attLen = 0; System.out.print("<" + name); if (attrs != null && ((attLen = attrs.getLength()) > 0)) { for (int i = 0; i < attLen; i++) { System.out.print(" " + attrs.getName(i) + "='"); System.out.print(attrs.getValue(i) + "'"); } } System.out.print(">"); } public void endElement (String name) { System.out.print("</" + name + ">"); } public void characters (char ch[], int start, int length) { System.out.print("Characters: \""); for (int i = start; i < start + length; i++) { switch (ch[i]) { case '\\': System.out.print("\\\\"); break; case '"': System.out.print("\\\""); break; case '\n': System.out.print("\\n"); break; case '\r': System.out.print("\\r"); break; case '\t': System.out.print("\\t"); break; default: System.out.print(ch[i]); break; } } System.out.print("\"\n"); } public void ignorableWhitespace (char ch[], int start, int length) { System.out.println("Ignorable Whitespace gefunden!"); } public void processingInstruction (String target, String data) { System.out.println("Processing Instruction gefunden!"); } public void setDocumentLocator (Locator locator) { System.out.println("setDocumentLocator aufgerufen!"); this.locator = locator; } private void printloc() { System.out.println("LocLine: " + locator.getLineNumber()); System.out.println("LocCol : " + locator.getColumnNumber()); } } class MeinErrorHandler implements ErrorHandler { public void warning (SAXParseException exception) { print("Warning", exception); } public void error (SAXParseException exception) { print("Warning", exception); } public void fatalError (SAXParseException exception) { print("Warning", exception); } private void print(String label, SAXParseException e) { System.err.println("** Parser " + label + ": " + e.getMessage()); System.err.println(" Line: " + e.getLineNumber()); System.err.println(" Column: " + e.getColumnNumber()); System.err.println(" URI: " + e.getSystemId()); System.err.println(" PUBLIC id: " + e.getPublicId()); } }