Searching...
Saturday, 18 January 2014

How to load properties from xml file in java?

19:57

Input XML file

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>Property details</comment>
	<entry key="location">bangalore</entry>
	<entry key="name">pretech</entry>
</properties>

Example

package com.pretech;
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 JavaReadXMLProperties {
	public static void main(String[] args) {
		Properties pr = null;
		try {
			pr = new Properties();
			InputStream is = new FileInputStream("test.xml");
			pr.loadFromXML(is);
			is.close();
			System.out.println("Property values are ::");
			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



Property values are ::
location:bangalore
name:pretech

0 comments: