Read Properties from XML with Java

On April 26, 2013, in Java, Programming, by LuCuS

Read properties from XML using Java.

properties.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="PROPERTY_1">This is property 1.</entry>
    <entry key="PROPERTY_2">This is property 2.</entry>
</properties>

PropertyManager.java

import java.io.InputStream;
import java.util.Properties;

public class PropertyManager
{
	public static String getProperty (String propertyName)
	{
		Properties props = new Properties();
		InputStream is = PropertyManager.class.getClassLoader().getResourceAsStream("properties.xml");
		try
		{
			props.loadFromXML(is);
			return props.getProperty(propertyName);
		}
		catch (Exception e)
		{
			return null;
		}
	}
}

Test.java

public class Test
{
	public static void main (String[] args) throws Exception
	{
		String property1 = PropertyManager.getProperty("PROPERTY_1");
		String property2 = PropertyManager.getProperty("PROPERTY_2");
		// DO SOMETHING WITH PROPERTIES
	}
}

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply