Search code examples
javaxmlxpathapache-commonsapache-commons-config

Query empty XML elements with attributes using apache commons configuration xpath


I'm using the apache commons configuration XMLConfiguration object with the XPATH expression engine to query an XML file. I am new to xpath and apache commons and am having trouble with the syntax.

The xml file looks like:

<attrs>
    <attr name="my_name" val="the_val"/>
    <attr name="my_name2" val="the_val2"/>
</attrs>

What I want to do basically is with commons loop through all the attributes and read name and val at each line. The only way I could work out to grab everything is to query the xml again with the value of name. This sort of feels wrong to me, is there a better way to do it?

List<String> names = config.getList("attrs/attr/@name");
for( String name : names )
{
    String val = config.getString("attrs/attr[@name='" +name +"']/@val" );
    System.out.println("name:" +name +"   VAL:" +val);
}

Also the conversion up top to String, I'm not sure the proper way to deal with that.


Solution

  • One option is to select the attr elements and iterate those as HierarchicalConfiguration objects:

    List<HierarchicalConfiguration> nodes = config.configurationsAt("attrs/attr");
    for(HierarchicalConfiguration c : nodes ) {
        ConfigurationNode node = c.getRootNode();
        System.out.println(
            "name:" + ((ConfigurationNode) 
                                node.getAttributes("name").get(0)).getValue() +
            " VAL:" + ((ConfigurationNode) 
                                node.getAttributes("val").get(0)).getValue());
    }
    

    That's not very pretty, but it works.