Skip to content

Loading a simple XML configuration file in Java made even simpler

Through the necessity 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. The Class also transparently allows for String interpolation, should it be required. You will find the mentioned Class below, followed by an example demonstrating its use.

import java.util.Properties;

 * A simple key:value map reader populated by an external XML stream
 * @author Jonathan Weatherhead
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);

The Properties Class that backs the SymbolMap class show above is truly useful, 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. The result is a powerful Class whose applications include externalized GUI messages, persistent configuration files, and object serialization. You will find the DTD for the required XML format in the Properties Class documentation. Now I will demonstrate how to use the SymbolMap class.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "">
<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>


public class Example {

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

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

public static void print(String s) {


The output:

> Hello, world!
> The cow says mooooo

2 thoughts on “Loading a simple XML configuration file in Java made even simpler

Leave a Reply

Your email address will not be published. Required fields are marked *