Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > JAVA TUTORIALS > TAMING TIGER: LOADING PROPERTIES FROM XML


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Taming Tiger: Loading Properties from XML
By John Zukowski - 2004-04-26 Page:  1 2 3 4

XML property files

None of this should be new to you. This is how the Properties class has always worked. What is new, however, is the option of loading a set of properties from an XML file. The DTD for that is shown in Listing 4.

Listing 4. Properties DTD

<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for properties -->
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>

If you're not into reading XML DTDs, this essentially says that wrapped within an outer <properties> tag is a <comment> tag, followed by any number of <entry> tags. For each <entry> tag, there is a key attribute, with the contents of the entry being its value. Listing 5 shows what the XML version of the properties file in Listing 1 would look like.

Listing 5. XML version of the Properties file


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>

</properties>

As Listing 6 shows, reading the XML version of the Properties file isn't much different than reading the older style format.

Listing 6. Reading the XML Properties file

import java.util.*;
import java.io.*;

public class LoadSampleXML {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis =
      new FileInputStream("sampleprops.xml");
    prop.loadFromXML(fis);
    prop.list(System.out);
    System.out.println("\nThe foo property: " +
        prop.getProperty("foo"));
  }
}

A note about resource bundles
While the java.util.Properties class now supports properties files as XML files in addition to key-value pairs, unfortunately, there is no built-in option available to treat a ResourceBundle as an XML file. Yes, a PropertyResourceBundle does use a Properties object to load the bundle; however, the use of the load method is hard-coded into the class, and the newer loadFromXML() method is not used.

Running the program in Listing 6 produces the same output as the original program, which is shown in Listing 2.



View Taming Tiger: Loading Properties from XML Discussion

Page:  1 2 3 4 Next Page: Saving XML Properties

First published by IBM developerWorks


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.