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
Java XML Parser - DOM DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With