Previous Section  < Day Day Up >  Next Section

Reading an XML File

As you have discovered during the first 20 hours, 13 minutes, and 52 seconds of this book, there's a wealth of Java code that's already written for you.

This code simplifies your job greatly. Within the Java 2 class library, you can adopt Swing classes for graphical user interface programming, the java.io classes for file access, java.awt.event to take user input, and take on other classes to do as little actual coding of your own as absolutely necessary.

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 simpler than coding your own classes from scratch.

Sun Microsystems isn't the only developer producing terrific Java classes, which you'll see during the remainder of this hour by using the XML Object Model (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 may 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.

The library can be downloaded from the website http://www.cafeconleche.org/XOM. After downloading and installing the library, you can use it in Java programs by adding the file xom-1.0.jar to your Classpath environment variable.

Watch Out!

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. The full details of the license can be viewed on the Web at http://www.cafeconleche.org/XOM/license.xhtml.


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

The next program that you create is the PropertyFileReader application, which reads the property.xml file that employs Sun's properties XML dialect.

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 properties file with it:


File propFile = new File("properties.xml");

Builder builder = new Builder();

Document doc = builder.build(propFile);


When the builder loads XML data, it makes it available as a Document object, which holds an entire XML document.

The document's root element can be retrieved with its getrootElement() method:


Element root = doc.getRootElement();


The Element class represents a single element. Each element has several methods that can be used to examine its contents:

  • The getFirstChildElement() method grabs the first child matching a specified name.

  • The get() method reads an element matching a specified index, numbered in order from 0 up.

  • The getChildElements() method grabs all of 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 commentElement = root.FirstChildElement("comment");

comment = commentElement.getValue();


This approach doesn't work when several elements share the same name, as the entry element does.

For those, you can retrieve all of the elements and loop through them with a for loop:


Elements entries = root.getChildElements("entry");

for (int current = 0; current < entries.size(); current++) {

    Element entry = entries.get(current);

}


An element's attribute can be accessed with the getAttribute() method, which takes the attribute's name as an argument:


Attrbute key = entry.getAttribute("key");


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


String keyValue = key.getValue();


Put all of this together by entering the text of Listing 21.3, saving the code in the source file PropertyFileReader.java.

Listing 21.3. The Full Text of PropertyFileReader.java

 1: import java.io.*;

 2: import nu.xom.*;

 3:

 4: public class PropertyFileReader {

 5:     String comment;

 6:     String username;

 7:     String browser;

 8:     boolean showEmail;

 9:

10:     public PropertyFileReader() throws ParsingException, IOException {

11:         // get the XML document

12:         File propFile = new File("properties.xml");

13:         Builder builder = new Builder();

14:         Document doc = builder.build(propFile);

15:         // get the root element, <properties>

16:         Element root = doc.getRootElement();

17:         // get the <comment> element and store it in a variable

18:         Element commentElement = root.getFirstChildElement("comment");

19:         comment = commentElement.getValue();

20:         // get the <entry> elements

21:         Elements entries = root.getChildElements("entry");

22:         for (int current = 0; current < entries.size(); current++) {

23:             // get current <entry>

24:             Element entry = entries.get(current);

25:             // get entry's key attribute

26:             Attribute key = entry.getAttribute("key");

27:             String keyValue = key.getValue();

28:             // store attribute value in the proper variable

29:             if (keyValue.equals("username")) {

30:                 username = entry.getValue();

31:             }

32:             if (keyValue.equals("browser")) {

33:                 browser = entry.getValue();

34:             }

35:             if (keyValue.equals("showEmail")) {

36:                 String emailValue = entry.getValue();

37:                 if (emailValue.equals("yes")) {

38:                     showEmail = true;

39:                 } else {

40:                     showEmail = false;

41:                 }

42:             }

43:         }

44:     }

45:

46:     public void showProperties() {

47:         System.out.println("\nProperties\n");

48:         System.out.println("Comment: " + comment);

49:         System.out.println("Username: " + username);

50:         System.out.println("Browser: " + browser);

51:         System.out.println("Show Email: " + showEmail);

52:     }

53:

54:     public static void main(String[] arguments) {

55:         try {

56:             PropertyFileReader reader = new PropertyFileReader();

57:             reader.showProperties();

58:         } catch (Exception exception) {

59:             System.out.println("Error: " + exception.getMessage());

60:         }

61:     }

62: }


Compile and run the PropertyFileReader application, which requires no command-line arguments. The program produces the following output, adjusted for the date and time that it was run:


Properties



Comment: Created on Sun Jul 10 21:18:33 EDT 2005

Username: rcade

Browser: Mozilla Firefox

Show Email: false


Watch Out!

You may encounter an error, depending on whether Sun has fixed a problem with the document type declaration file http://java.sun.com/dtd/properties.dtd, which is referenced in Line 2 of Listing 21.2. To resolve the problem, delete this line and save the file.


    Previous Section  < Day Day Up >  Next Section