XML Parsing
import java.io.FileReader; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.DefaultHandler; /** Our handler must extend DefaultHandler */ public class MySAXApp extends DefaultHandler { public static void main (String args[]) throws Exception { //Create an instance of the XML parser. XMLReader xr = XMLReaderFactory.createXMLReader(); //Create an instance of our handles (see below) MySAXApp handler = new MySAXApp(); xr.setContentHandler(handler); xr.setErrorHandler(handler); //does double duty. // Parse each *file* provided on the // command line. for (int i = 0; i < args.length; i++) { FileReader r = new FileReader(args[i]); xr.parse(new InputSource(r)); } } public MySAXApp () { super(); } //////////////////////////////////////////////////////////////////// // Event handlers. //////////////////////////////////////////////////////////////////// public void startDocument () { System.out.println("Start document"); } public void endDocument () { System.out.println("End document"); } /** * Receive notification at the beginning of an element. * * @param uri The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed. * @param name The local name (without prefix), or the empty string if Namespace processing is not being performed. * @param qName The qualified name (with prefix), or the empty string if qualified names are not available.[namespaceprefix:name] * @param atts The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object. */ public void startElement (String uri, String name, String qName, Attributes atts) { if ("".equals (uri)) System.out.println("Start element: " + qName); else System.out.println("Start element: {" + uri + "}" + name); } public void endElement (String uri, String name, String qName) { if ("".equals (uri)) System.out.println("End element: " + qName); else System.out.println("End element: {" + uri + "}" + name); } /** * Receive notification of character data. * * @param ch[] The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array */ 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"); } }
3 of 16