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


An example of writing key/value pairs from a Properties object to a properties file is described in another lesson. Here, we'll show how we can instead write to an XML-formatted properties file.

Let's create a WritePropertiesXmlFile class to write key/value pairs in a Properties object to a 'test2.xml' file at the root level of our project.

'testing' project

The WritePropertiesXmlFile class is just like our WritePropertiesFile class that we described in another tutorial, except that it writes to 'test2.xml' rather than to 'test2.properties' and we call the Properties object's storeToXML method rather than its store method.

WritePropertiesXmlFile.java

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class WritePropertiesXmlFile {
	public static void main(String[] args) {
		try {
			Properties properties = new Properties();
			properties.setProperty("favoriteAnimal", "marmot");
			properties.setProperty("favoriteContinent", "Antarctica");
			properties.setProperty("favoritePerson", "Nicole");

			File file = new File("test2.xml");
			FileOutputStream fileOut = new FileOutputStream(file);
			properties.storeToXML(fileOut, "Favorite Things");
			fileOut.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

When WritePropertiesXmlFile is executed, it generates the test2.xml file based on the contents of the Properties object. The results are displayed below.

test2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Favorite Things</comment>
<entry key="favoriteContinent">Antarctica</entry>
<entry key="favoriteAnimal">marmot</entry>
<entry key="favoritePerson">Nicole</entry>
</properties>

As you can see, creating an XML-formatted properties file from a Properties object is extremely easy.