Java Reference
In-Depth Information
The bulk of the work is done in the class's parse method, which takes a byte stream
from which to read XML. It creates an instance of KXmlParser , sets the parser to read from
the InputStream it derives from the incoming byte stream, and then begins reading tags
from the parser in a while loop. The loop just uses a switch / case statement to generate
parser events for the kind of XML token the parser has encountered, invoking event han-
dlers I derive from the LocationParserHandler implementation.
Each of the parser's event handlers takes an instance of the KXmlParser , so that it
can query the parser for more information about the event, such as the name of the tag
encountered (which getName returns), the value of an attribute (which getAttributeValue
returns), or the character data the parser encountered within a tag (which getText returns).
Using the kXML-enabled LocationParser in WeatherWidget is almost exactly the
same as using the JSR 172 SAX parser, as you see in Listing 13-13.
Listing 13-13. Using the kXML Parser and the LocationParser Class
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) {
LocationParser parser = new LocationParser(this);
byte[] xmlBytes;
ByteArrayInputStream bis;
xmlBytes = xml.getBytes();
bis = new ByteArrayInputStream(xmlBytes);
try {
parser.parse(bis);
}
catch(Exception e){}
finally {
try {
bis.close();
}
catch(Exception e) {}
}
}
}
 
Search WWH ::




Custom Search