Skip to content

Loading a simple XML configuration file in Java made even simpler

A quick implementation for reading a key/value dataset from an XML document.

I had to externalize GUI messages in an application that I have been working on, I have come up with a remarkably simple and clean approach for loading key:value pairs from an external XML file or stream.

My implementation also transparently allows for String interpolation, should it be required.

Implementation

import java.io.File;
import java.util.Properties;

public class SymbolMap {
  private Properties symbolmap;

  public SymbolMap( File file ) {
    symbolmap = new Properties();

    try {
      // Populate the symbol map from the XML file
      symbolmap.loadFromXML( file.toURI().toURL().openStream() );
    }
    catch ( Exception e ) {
    }
  }

  /*
  variable length arguments are packed into an array
  which can be accessed and passed just like any array
  */
  public String lookupSymbol( String symbol, String... variables ) {
    // Retrieve the value of the associated key
    String message = symbolmap.getProperty( symbol );

    if( message == null ) {
      return "";
    }

    // Interpolate parameters if necessary and return the message
    return String.format( message, variables );
  }
}

I leverage Java’s Properties Class to back the SymbolMap implementation, hiding all of the stream reading and XML processing concerns, as well as providing a map-based structure to access the values with their respective keys.

To use this implementation, your XML file must follow a specific DTD – you will find the DTD for the required XML format in the Properties Class documentation.

Example use of SymbolMap

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>example pairs</comment>
<entry key="MOTD">Hello, world!</entry>
<entry key="FAVOURITE_FRUIT">Mango</entry>
<entry key="THE_COW_SAYS">The cow says %s</entry>
</properties>
import java.io.File;

public class Example {

  public static void main( String[] args ) throws Exception {
    SymbolMap symbolmap = new SymbolMap( new File( "example.xml" ) );

    print( "> " + symbolmap.lookupSymbol( "MOTD" ) );
    print( "> " + symbolmap.lookupSymbol( "NOT_FOUND" ) );
    print( "> " + symbolmap.lookupSymbol( "THE_COW_SAYS", "mooooo" ) );
  }

  public static void print(String s) {
    System.out.println( s );
  }

}

The output:

> Hello, world!
>
> The cow says mooooo