Java Reference
In-Depth Information
setDocumentLocator(Locator locator)
Called by the parser to pass a Locator
object to your code that you can use to
determine the location in the document of
any SAX document event. The Locator
object can provide the public identifier, the
system ID, the line number, and the column
number in the document for any event. Just
implement this method if you want to
receive this information for each event.
Your implementations of these methods can throw an exception of type SAXException if an error occurs.
The DefaultHandler class is just like the adapter classes we have used for defining GUI event
handlers. All we have to do to implement our own handler is extend the DefaultHandler class, and
define our own implementations for the methods we are interested in. The same caveat applies here that
applied with adapter classes - you must take care that the signatures of your methods are correct.
Otherwise you are simply adding a new method rather than overriding one of the inherited methods. In
this case your program will then do nothing for the given event since the original do-nothing version of
the method will execute rather than your version. Let's try implementing a handler class.
Try It Out - Handling Parsing Events
Let's first define a handler class to deal with document parsing events. We will just implement a few of
the methods from the ContentHandler interface - only those that apply to a simple document - and
we will not worry about errors for the moment. Here's the code:
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
public class MySAXHandler extends DefaultHandler {
public void startDocument() {
System.out.println("Start document: ");
}
public void endDocument() {
System.out.println("End document: ");
}
public void startElement(String uri, String localName,
String qname, Attributes attr) {
System.out.println("Start element: local name: " + localName + " qname: "
+ qname + " uri: "+uri);
}
public void endElement(String uri, String localName, String qname) {
System.out.println("End element: local name: " + localName + " qname: "
+ qname + " uri: "+uri);
}
public void characters(char[] ch, int start, int length) {
System.out.println("Characters: " + new String(ch, start, length));
Search WWH ::




Custom Search