Alex Rivera | Logout

How to read properties from xml file with java?

Asked 2011-12-15T23:29:09.973
16

I have the following xml file:

<resources>
    <resource id="res001">
        <property name="propA" value="A" />
        <property name="propB" value="B" />
    </resource>
    <resource id="res002">
        <property name="propC" value="C" />
        <property name="propD" value="D" />
    </resource>
    <resource id="res003">
        <property name="propE" value="E" />
        <property name="propF" value="F" />
    </resource>
</resources>

How can I do something like this with Java/Xml:

Xml xml = new Xml("my.xml");
Resource res001 = xml.getResouceById("res003");
System.out.println("propF: " + res.getProperty("propF"));

So it prints:

F

I have tried apache commons-configurations XMLConfiguration with XPathExpressionEngine, but I just can't make it work. I have googled and found some examples, but neither would work :( I'm looking for a solution where I don't need to loop through all the elements.

Regards, Alex

Edit
Report

2 Answers

19

This is trivial, assuming you're willing to re-write your properties file into the standard Java format. Assume you have the following in a file called props.xml:

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>This is a comment</comment>
    <entry key="propA">A</entry>
    <entry key="propB">B</entry>
    <entry key="propC">C</entry>
    <entry key="propD">D</entry>
    <entry key="propE">E</entry>
    <entry key="propF">F</entry>
</properties>

Then read properties from the file like this:

java.util.Properties prop = new Properties();
prop.loadFromXML(new FileInputStream("props.xml"));
System.out.println(prop.getProperty("propF"));
answered 2011-12-16T21:53:56.560
1

I would just use JAXB to bind data into set of objects that have structure similar to your XML document.

Something like:

@XmlRootElement("resources")
public class Resources {
  public List<Resource> resource = new ArrayList<Resource>(); // important, can't be left null
}
public class Resource {
  @XmlAttribute public String id;
  public List<Property> property;
}
// and so on

one possible gotcha is regarding List serialization; there are two modes, wrapped and unwrapped; in your case, you want "unwrapped". Javadocs for annotations should show annotation to define this.

answered 2011-12-16T00:00:50.563

Your Answer