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
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. The ReadPropertiesXmlFile class is just like our ReadPropertiesFile class that we described in another tutorial, except that it reads 'test.xml' rather than 'test.properties' and we call the Properties object's loadFromXML method rather than its load method. ReadPropertiesXmlFile.javapackage test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; 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(); properties.loadFromXML(fileInput); fileInput.close(); 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) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } The contents of test.xml are displayed below. test.xml<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Here are some favorites</comment> <entry key="favoriteSeason">summer</entry> <entry key="favoriteFruit">pomegranate</entry> <entry key="favoriteDay">today</entry> </properties> (Continued on page 2) |