Java Collection How to - Store properties as XML file








Question

We would like to know how to store properties as XML file.

Answer

import java.io.FileOutputStream;
import java.util.Properties;
/*w  ww.  jav  a 2 s  . c om*/
public class Main {
  public static void main(String[] args) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("database.type", "mysql");
    properties.setProperty("database.url", "jdbc:mysql://localhost/mydb");
    properties.setProperty("database.username", "root");
    properties.setProperty("database.password", "root");

    FileOutputStream fos = new FileOutputStream("database-configuration.xml");
    properties.storeToXML(fos, "Database Configuration", "UTF-8");
  }
}

The saved XML file will look like the properties file below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd
  <properties>
    <comment>Database Configuration</comment>
    <entry key="database.passwordroot</entry>
    <entry key="database.urljdbc:mysql://localhost/mydb</entry>
    <entry key="database.typemysql</entry>
    <entry key="database.usernameroot</entry>
  </properties>