javaxmlapache-commonsxml-configuration

Apache Commons XMLConfiguration- How to Get an Object by Attribute Name?


I am using org.apache.commons.configuration.XMLConfiguration to read the an XML configuration file in my Java code. My XML has the following format:

<items>
    <item name = "cherry">
        <colour >red</colour >
    </item>

    <item name = "apple">
        <colour >green</colour >
    </item>
</items>

I want to get the colour value of an item named 'cherry'. I have tried this:

config.getString("items.item[@name=cherry].colour");

But it doesn't work, any suggestions?


Solution

  • From Code Thrill weblog, I found that I need to set the expression engine to XPath by config.setExpressionEngine(new XPathExpressionEngine());

    which needs the commons-jxpath library.

    Then I can get the result using XPath like this:

    config.getString("items/item[@name='cherry']/colour");