Java Reference
In-Depth Information
character data it's accumulated should go,
null
ing out the
StringBuffer
it used for that
accumulation once it has stored the buffer's contents in the appropriate field of
location
.
The SAX parser invokes your handler's
endDocument
when it encounters the end
of your document; this is another opportunity to update the variables you're using to
store the parsed XML data. The
LocationParserHandler
method doesn't need to do this,
because it's updating
location
throughout the parse operation, so its
endDocument
is an
empty method.
■
Note
You don't need to provide any of these methods if your class doesn't do anything with the SAX
event the method represents; in Listing 13-8, I include
endDocument
for clarity and completeness, but it's
not really necessary.
Using the SAX parser is simple: you instantiate the parser and location handler,
and you provide a stream with the parser handler to the parser for it to parse. Listing 13-9
shows this process in the
Location
class's
fromXml
method, which takes an XML docu-
ment and sets the values of its fields to the values specified in the document using the
SAX parser.
Listing 13-9.
Using the SAX Parser Provided by JSR 172
package com.apress.rischpater.weatherwidget;
import javax.microedition.rms.*;
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Location {
/* other methods from Listing 13-7 */
public void fromXml(String xml) {
SAXParser parser = null;
LocationParserHandler handler = new LocationParserHandler(this);
byte[] xmlBytes;
ByteArrayInputStream bis;
try {
SAXParserFactory f = SAXParserFactory.newInstance();
parser = f.newSAXParser();
}