Tuesday, 6 March 2012

java program to read properties xml file

userinfo.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>User Info</comment>
<entry key="age">38</entry>
<entry key="password">india@123</entry>
<entry key="username">sachin</entry>
</properties>


package com.usr.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class ReadPropertiesXmlFile {
       public static void main(String[] args) {
              Properties pr = new Properties();
              try {
                     InputStream is = new FileInputStream("userinfo.xml");
                     pr.loadFromXML(is);
                     is.close();

                     Enumeration enumKeys = pr.keys();
                     while (enumKeys.hasMoreElements()) {
                           String key = (String) enumKeys.nextElement();
                           String value = pr.getProperty(key);
                           System.out.println(key + ":" + value);
                     }
              } catch (FileNotFoundException ex) {
                     ex.printStackTrace();
              } catch (IOException ex) {
                     ex.printStackTrace();
              }
       }
}
OUTPUT
age:38
password:india@123
username:sachin