XMLProperties

Let’s take things to the next logical step, and look at reading XML. Continuing with the example of converting a properties file to XML, you are now probably wondering how to access the information in your XML file. Luckily, there’s a solution for that, too! In this section, for the sake of explaining how JDOM reads XML, I want to introduce a new utility class, XMLProperties. This class is essentially an XML-aware version of the Java Properties class; in fact, it extends that class. This class allows access to an XML document through the typical property-access methods like getProperty( ) and properties( ); in other words, it allows Java-style access (using the Properties class) to XML-style storage. In my opinion, this is the best combination you can get.

To accomplish this task, you can start by creating an XMLProperties class that extends the java.util.Properties class. With this approach, making things work becomes simply a matter of overriding the load( ), save( ), and store( ) methods. The first of these, load( ) , reads in an XML document and loads the properties within that document into the superclass object.

Warning

Don’t mistake this class for an all-purpose XML-to-properties converter; it only will read in XML that is in the format detailed earlier in this chapter. In other words, properties are elements with either textual or attribute values but not both; I’ll cover both approaches, but you’ll have to choose one or the other. Don’t try to take all ...

Get Java and XML, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.