Reading XML properties can be easily done using the java.util.Properties.loadFromXML()
method. Just like reading the properties from a file that contains a key=value pairs, the XML file will also contain a key and value wrapped in the following XML format.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Application Configuration</comment>
<entry key="data.folder">D:\AppData</entry>
<entry key="jdbc.url">jdbc:mysql://localhost/kodejava</entry>
</properties>
package org.kodejava.util;
import java.util.Properties;
public class LoadXmlProperties {
public static void main(String[] args) {
LoadXmlProperties demo = new LoadXmlProperties();
try {
Properties properties = demo.readProperties();
//Display all properties information
properties.list(System.out);
// Read the value of data.folder and jdbc.url configuration
String dataFolder = properties.getProperty("data.folder");
System.out.println("data.folder = " + dataFolder);
String jdbcUrl = properties.getProperty("jdbc.url");
System.out.println("jdbc.url = " + jdbcUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
private Properties readProperties() throws Exception {
Properties properties = new Properties();
properties.loadFromXML(getClass().getResourceAsStream("/configuration.xml"));
return properties;
}
}
The result of the code snippet above:
-- listing properties --
data.folder=D:\AppData
jdbc.url=jdbc:mysql://localhost/kodejava
data.folder = D:\AppData
jdbc.url = jdbc:mysql://localhost/kodejava