Query empty XML elements with attributes using apache commons configuration xpath

3k views Asked by At

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.

2

There are 2 answers

1
Wayne On BEST ANSWER

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.

1
grv On

How can get the value of the tag which matches to a given attribute like in this xml sample using commons XML configuration?

<attrs>
    <attr name="my_name"> First Name</attr>
    <attr name="my_name2"> First Name 2 </attr>
</attrs>

Want to get the value First Name for a matching my_name attribute value