Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons XMLConfiguration - how to fetch a list of objects at a given node?

I have an XML configuration file similar to this:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<config>
    <mainServerHostname>MainServer</mainServerHostname>
    <failoverServers>
        <server>
            <ipAddress>192.168.0.5</ipAddress>
            <priority>1</priority>
        </server>
        <server>
            <ipAddress>192.168.0.6</ipAddress>
            <priority>2</priority>
        </server>
    </failoverServers>
</config>

Now, I know that by using the following code (after setting up my XMLConfiguration object and calling it config):

config.getList("failoverServers.server.ipAddress");

I can get a list of all of the ip addresses. This is handy, but what would be even more handy would be if I could do something like this:

config.getList("failoverServers.server");

and get a list of Objects, each of which has an ipAddress and a priority. As far as I can tell though, there is no way to do this. Does anyone have any ideas on how I could accomplish this type of functionality? I would even be perfectly willing to define data structures corresponding to the structure of the XML that Java could map the data into if that would make things easier (in fact that would probably even be better). Thanks for the help all!

like image 706
Brendon Dugan Avatar asked Jan 17 '13 21:01

Brendon Dugan


1 Answers

You can use HierarchicalConfiguration instead of XMLConfiguration. Works like this:

List<HierarchicalConfiguration> servers = config.configurationsAt("failoverServers.server");
for(HierarchicalConfiguration server : servers) {
    System.out.println(server.getString("ipAddress"));
}

See: http://commons.apache.org/configuration/userguide/howto_xml.html

like image 81
theadam Avatar answered Sep 25 '22 13:09

theadam