Java Reference
In-Depth Information
The string after the trailing / is the URL-safe encoding of a unique location (in this
case, “Berkeley, CA, USA”). The WeatherFetcher class accomplishes this mapping at the
beginning of run , where it creates the URL using the URL prefix for the service statically
defined by the class and its requestEncode method. Next, it creates an HttpConnection with
a method GET , and reads the response into a string for the Location instance to parse.
Tip Although this example uses more RAM to read the entire document into memory and then parse
it, it's easier to debug, because the XML obtained by the web service client can be written to a debug file
or elsewhere during development. I could have just as easily crafted the Location class to take an
InputStream for the fromXml argument and passed the HttpConnection 's InputStream instance
directly to the Location instance for parsing, saving some memory. You may want to consider this approach
when you need to parse large XML documents, because it's possible that the underlying SAX parser won't
need to read the entire document into memory during the parse operation.
Introducing the kXML Parser
As I note in the beginning of the previous section, the XML parser provided by JSR 172 is
optional (in fact, all of JSR 172 is optional!), and it's quite likely that you will encounter
devices that don't provide a SAX parser. Fortunately, there's a lightweight alternative,
kXML, available under a generous license at http://kxml.sourceforge.net . To use the
parser, download the JAR file implementing the kXML parser and include it in your Net-
Beans project using the Properties inspector (see Figure 13-3).
The kXML package is now starting its third iteration; as I write this, kXML version 1
is deprecated, and kXML version 2 is the version people should use while the team
develops version 3. kXML version 2 implements a classic pull parser in the org.kxml2.io
package with the KXmlParser class. Using this class, you pull items from a stream contain-
ing XML using the various next methods:
next : Returns the type of the next XML token in the stream
nextTag : Returns the name of the next tag in the stream
nextText : Returns the contents of the next CDATA region in the stream
nextToken : Returns the next XML token in the stream
This approach—pulling tags from the source stream rather than having events sent
to a new class—may marginally reduce the amount of code you have to write and ship,
although many developers may find it less clear than the SAX push parser you saw in the
previous section. As you will soon see in Listing 13-12, it's easy to construct a wrapper
around a pull parser that looks very much like a push parser.
 
Search WWH ::




Custom Search