Reading an XML File

As you have discovered during the first 20 hours, 13 minutes, and 52 seconds of this book, a wealth of Java code is already written for you to greatly simplify your job. Within the Java class library, you can adopt Swing classes for user interface programming, the java.io classes for file access, java.awt.event to take user input, and other classes to do as little programming of your own as possible.

A vital skill to develop in your Java programming is to learn where to look for Java classes and packages you can employ in your own projects. Reusing a well-developed class library is considerably easier than coding your own classes from scratch.

The Java team at Oracle isn’t the only developer producing terrific Java classes, which you see during the remainder of this hour by using XOM, a class library developed by the computer programmer and book author Elliotte Rusty Harold. Harold, an expert in both the Java language and XML, grew frustrated with how existing XML libraries worked. (You might be sensing a theme here—Java itself was developed by James Gosling as an expression of his frustration with another language.)

Harold created his own class library that represents XML data as a tree holding each element as a node.

You can download the library from www.xom.nu.

Unpack the archive in a folder on your system. I used C:\java\XOM on my Windows XP system, devoting the top-level folder C:\java to Java libraries I use. After downloading and unpacking a library, you must add it to your current project in NetBeans:

1. Choose File, Project Properties. The Project Properties dialog opens.

2. Click Libraries in the Categories pane, and then click the Add Library button. The Add Library dialog opens.

3. Click the Create button. The Create New Library dialog opens.

4. Enter XOM in the Library Name field and click OK. The Customize Library dialog opens.

5. Click Add JAR/Folder. The Browser JAR/Folder dialog opens.

6. Find the folder where you saved XOM and choose the xom-1.2.1 and xom-samples files. (The version number of XOM might be different.) Click Add JAR/Folder.

7. In the Customize Library dialog, click OK.

8. In the Add Library dialog, choose XOM and click Add Library.

9. In the Project Properties dialog, click OK.


Caution

XOM has been made available at no cost under an open source license, the GNU Lesser General Public License (LGPL). You can distribute the XOM library without modification with Java applications that rely on it.

You also can make changes to the classes in the library, but you must make these changes available under the LGPL. You can view the full details of the license at www.xom.nu/license.xhtml.


The XOM library is now available to your project.

XOM has classes to read and write XML data, saving it to files and other destinations.


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 difficult 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 forecast for Wasilla, Alaska.


The next program you create is the WeatherStation application, which reads forecast information offered in an XML dialect by the Weather Underground website, which is available at www.wunderground.com.

The core classes of the XOM library are in the nu.xom package, made available in your programs with an import statement:

import nu.xom.*;

The Builder class can load and parse XML data 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 XML data 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 XML data, it makes it available as a Document object, which holds an entire XML document.

You can retrieve the document’s root element with its getRootElement() method:

Element root = doc.getRootElement();

The Element class 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 comment element and its value:

Element highF = high.FirstChildElement("fahrenheit");
String highTemp = highF.getValue();

This approach doesn’t work when several elements share the same name, as the forecastday element does. For those, you can retrieve all the elements and loop through them with a for loop:

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 called WeatherStation and enter the text from Listing 21.3 into the file.

Listing 21.3. The Full Text of WeatherStation.java


 1: import java.io.*;
 2: import nu.xom.*;
 3:
 4: public class WeatherStation {
 5:     int[] highTemp = new int[6];
 6:     int[] lowTemp = new int[6];
 7:     String[] conditions = new String[6];
 8:
 9:     public WeatherStation() throws ParsingException, 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, <forecast>
14:         Element root = doc.getRootElement();
15:         // get the <simpleforecast> element
16:         Element simple = root.getFirstChildElement("simpleforecast");
17:         // get the <forecastday> elements
18:         Elements days = simple.getChildElements("forecastday");
19:         for (int current = 0; current < days.size(); current++) {
20:             // get current <forecastday>
21:             Element day = days.get(current);
22:             // get current <high>
23:             Element high = day.getFirstChildElement("high");
24:             Element highF = high.getFirstChildElement("fahrenheit");
25:             // get current <low>
26:             Element low = day.getFirstChildElement("low");
27:             Element lowF = low.getFirstChildElement("fahrenheit");
28:             // get current <icon>
29:             Element icon = day.getFirstChildElement("icon");
30:             // store values in object variables
31:             lowTemp[current] = -1;
32:             highTemp[current] = -1;
33:             try {
34:                 lowTemp[current] = Integer.parseInt(lowF.getValue());
35:                 highTemp[current] = Integer.parseInt(highF.getValue());
36:             } catch (NumberFormatException nfe) {
37:                 // do nothing
38:             }
39:             conditions[current] = icon.getValue();
40:         }
41:     }
42:
43:     public void display() {
44:         for (int i = 0; i < conditions.length; i++) {
45:             System.out.println("Period " + i);
46:             System.out.println(" Conditions: " + conditions[i]);
47:             System.out.println(" High: " + highTemp[i]);
48:             System.out.println(" Low: " + lowTemp[i]);
49:         }
50:     }
51:
52:     public static void main(String[] arguments) {
53:         try {
54:             WeatherStation station = new WeatherStation();
55:             station.display();
56:         } catch (Exception exception) {
57:             System.out.println("Error: " + exception.getMessage());
58:         }
59:     }
60: }


The WeatherStation application, which requires no command-line arguments, produces seven forecasts for Wasilla, Alaska, as in the following output:

Output


Period 0
    Conditions: rain
    High: 56
    Low: 40
Period 1
    Conditions: partlycloudy
    High: 59
    Low: 40
Period 2
    Conditions: partlycloudy
    High: 61
    Low: 41
Period 3
    Conditions: chancerain
    High: 67
    Low: 43
Period 4
    Conditions: chancerain
    High: 67
    Low: 47
Period 5
    Conditions: chancerain
    High: 65
    Low: 49



Note

The Java class library includes the Java API for XML Processing (JAXP), a set of classes that serve the same purpose as XOM. JAXP can represent XML data as an object or a stream of events, giving a programmer more control over how the data is parsed. XOM is easier to learn and requires properly formatted and valid XML at all times. More information on JAXP can be found on the Web at http://jaxp.java.net.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.128.145