How do I read properties from an XML file?
Author: Deron Eriksson
Description: This Java tutorial describes how to read properties from an XML file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1

Page:    1 2 >

An example of reading key/value pairs from a properties file into a Properties object is described in another lesson. Interestingly, a properties file can actually be formatted in XMLW if desired. This format can also be conveniently loaded in a Properties object.

Let's say we have a 'test.xml' file at the root level of our project that we'd like to feed into a Properties object. Let's create a ReadPropertiesXmlFile class to do this.

'testing' project

The ReadPropertiesXmlFile class is just like our ReadPropertiesFile class that we described in another tutorial, except that it reads 'test.xml' rather than '' and we call the Properties object's loadFromXML method rather than its load method.

package test;

import java.util.Enumeration;
import java.util.Properties;

public class ReadPropertiesXmlFile {
	public static void main(String[] args) {
		try {
			File file = new File("test.xml");
			FileInputStream fileInput = new FileInputStream(file);
			Properties properties = new Properties();

			Enumeration enuKeys = properties.keys();
			while (enuKeys.hasMoreElements()) {
				String key = (String) enuKeys.nextElement();
				String value = properties.getProperty(key);
				System.out.println(key + ": " + value);
		} catch (FileNotFoundException e) {
		} catch (IOException e) {

The contents of test.xml are displayed below.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "">
<comment>Here are some favorites</comment>
<entry key="favoriteSeason">summer</entry>
<entry key="favoriteFruit">pomegranate</entry>
<entry key="favoriteDay">today</entry>

(Continued on page 2)

Page:    1 2 >