5

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.

James DeRagon
  • 364
  • 1
  • 4
  • 11
  • try this `attrs/attr/@name | //attr/@val` – RanRag Jan 11 '12 at 22:02
  • This got both values but in a long string list such that all the names came out, followed by all the values. While they are in order, you would have to probably do some maths like val_pos = size()/2 then get i + val_pos as you loop through. Not very clean but does save some queries. So far due to time constraints just going to stick to querying again for clarity, but still welcome a good way to loop over an xml file with commons that is in that format. – James DeRagon Jan 11 '12 at 22:21

2 Answers2

4

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.

Wayne
  • 59,728
  • 15
  • 131
  • 126
  • This does work indeed. I tried to time both functions and this one came out faster (nanoseconds). Original: 295,377,206 This: 12,712,510 Thank you! Will work with this method. – James DeRagon Jan 12 '12 at 15:51
0

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

grv
  • 31
  • 4