Parsing with SAX using Java Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University
168493: XML and Web Services (II/2546) 2 Overview of SAX The event-driven, serial-access mechanism for accessing XML documents, SAX This is the protocol that most servlets and network-oriented programs will want to use to transmit and receive XML documents Fastest and least memory
168493: XML and Web Services (II/2546) 3 Overview of SAX The SAX protocol requires a lot more programming than the DOM It’s also a bit harder to visualize because it is an event-driven model We cannot visit the data that we already visit because it is a serial data stream
168493: XML and Web Services (II/2546) 4 When Not to use SAX Developers who are writing a user- oriented application that displays an XML document and possibly modifies it will want to use the DOM mechanism
168493: XML and Web Services (II/2546) 5 Importing Classes import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationExce ption; import javax.xml.parsers.SAXParser;
168493: XML and Web Services (II/2546) 6 startDocument Event public void startDocument() throws SAXException { emit("<?xml version='1.0' encoding='UTF-8'?>"); nl(); }
168493: XML and Web Services (II/2546) 7 endDocument Event public void endDocument() throws SAXException { try { nl(); out.flush(); } catch (IOException e) { throw new SAXException("I/O error", e); }
168493: XML and Web Services (II/2546) 8 startElement Event public void startElement(String namespaceURI, String sName, // simple name String qName, // qualified name Attributes attrs) throws SAXException { … }
168493: XML and Web Services (II/2546) 9 endElement Event public void endElement(String namespaceURI, String sName, // simple name String qName, // qualified name) throws SAXException { … }
168493: XML and Web Services (II/2546) 10 characters Event public void characters( char buf[], int offset, int len) throws SAXException { String s = new String(buf, offset, len); … }