Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

304 HOUR 21: Reading and Writing XML Data


The next program you create is the WeatherStationapplication, which
reads forecast information offered in an XMLdialect by the Weather
Underground website, which is available at http://www.wunderground.com.
The core classes of the XOM library are in the nu.xompackage, made avail-
able in your programs with an importstatement:
importnu.xom.*;

The Builderclass can load and parse XMLdata in any dialect, as long as
it’s well formed.
Here’s the code to create a builder and load the forecast file with it:
File file = new File(“forecast.xml”);
Builder builder = new Builder();
Document doc = builder.build(propFile);

XOM also can load XMLdata over the Web. Instead of calling build(File),
call the method with the web address of the data, as in this code:
Builder builder = new Builder();
Document doc = builder.build(“http://tinyurl.com/rd4r72”);

When the builder loads XMLdata, it makes it available as a Document
object, which holds an entire XMLdocument.
You can retrieve the document’s root element with its getRootElement()
method:
Element root = doc.getRootElement();

The Elementclass represents a single element. Each element has several
methods that you can use to examine its contents:

. The getFirstChildElement()method grabs the first child matching
a specified name.
. The get(int)method reads an element matching a specified index,
numbered in order from 0 up.
. The getChildElements()method grabs all its child elements.
. The getValue()method reads its text.
. The getAttribute()method retrieves one of its attributes.


The following statements retrieve the commentelement and its value:
Element highF = high.FirstChildElement(“fahrenheit”);
String highTemp = highF.getValue();

NOTE
The web address
http://tinyurl.com/rd4r72 is a
shortened URL that redirects to
the actual address on the
Weather Underground site,
which is considerably more diffi-
cult to type in correctly. Here’s
the full address:
http://wunderground.com/auto
/wui/geo/ForecastXML/
index.xml?query=Wasilla,AK
This contains the weather fore-
cast for Wasilla,Alaska.

Free download pdf