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

(singke) #1
ptg7068951

Reading an XML File 305

This approach doesn’t work when several elements share the same name,
as the forecastdayelement does. For those, you can retrieve all the ele-
ments and loop through them with a forloop:


Elements days = root.getChildElements(“simpleday”);
for(int current = 0; current < days.size(); current++) {
Element day = days.get(current);
}


This program does not make use of attributes, but an element’s attribute
can be accessed with the getAttribute()method, which takes the
attribute’s name as an argument:


Attribute key = day.getAttribute(“key”);


When you have the attribute, its getValue()method reveals the matching
value:


String keyValue = key.getValue();


Create a new empty Java file calledWeatherStationand enter the text
from Listing 21.3 into the file.


LISTING 21.3 The Full Text of WeatherStation.java
1: importjava.io.;
2: importnu.xom.
;
3:
4: public classWeatherStation {
5: int[] highTemp= new int[6];
6: int[] lowTemp= new int[6];
7: String[] conditions= new String[6];
8:
9: publicWeatherStation() throwsParsingException, IOException {
10: // get the XML document
11: Builder builder = new Builder();
12: Document doc = builder.build(“http://tinyurl.com/rd4r72”);
13: // get the root element,
14: Element root = doc.getRootElement();
15: // get the element
16: Element simple = root.getFirstChildElement(“simpleforecast”);
17: // get the elements
18: Elements days = simple.getChildElements(“forecastday”);
19: for (int current = 0; current < days.size(); current++) {
20: // get current
21: Element day = days.get(current);
22: // get current
23: Element high = day.getFirstChildElement(“high”);
24: Element highF = high.getFirstChildElement(“fahrenheit”);
25: // get current

Free download pdf