Wednesday 1 August 2012

Convert XML File Into Properties File

Most of the Software developers may not aware of this function, actually, the java.util.Properties class come with a loadFromXML() method to load above XML file into a properties objec.
To convert properties file into XML file. See following XML file :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
   <properties>
 <comment>Support Email</comment>
 <entry key="email.support">me@sanjeetpandey.com</entry>
   </properties>

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
 
     InputStream is = new FileInputStream("c:/email-configuration.xml");
     //load the xml file into properties format
     props.loadFromXML(is);
 
     String email = props.getProperty("email.support");
 
     System.out.println(email);
 
    }
}

Output:

me@sanjeetpandey.com

Convert Properties File Into XML File

Most of the Software developers may not aware of this function, actually, the java.util.Properties class come with a storeToXML() method to convert existing properties data into a XML file.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
 
public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    { 
     Properties props = new Properties();
     props.setProperty("email.support", "me@sanjeetpandey.com");
 
     //where to store?
     OutputStream os = new FileOutputStream("c:/email-configuration.xml");
 
     //store the properties detail into a pre-defined XML file
     props.storeToXML(os, "Support Email","UTF-8");
 
     System.out.println("Done");
    }
}

The above example will write the properties detail into a XML file “c:/email-configuration.xml“.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 <properties>
  <comment>Support Email</comment>
  <entry key="email.support">me@sanjeetpandey.com</entry>
 </properties>