javaxpathapache-commons-config

How to query XMLConfiguration by value with XPath in Apache Commons Configuration?


So I have the following XML file.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<omg>
  <configurationCreated>23/05/20 01:19:30</configurationCreated>
  <sites>
    <site>
      <name>qwer1</name>
      <another>lol1</another>
    </site>
    <site>
      <name>qwer2</name>
      <another>lol2</another>
    </site>
  </sites>
</omg>

I am trying to query the site with name qwer2 in order to check whether it already exists inside the file. How do I do this?

This is what I tried in Java (I kinda followed this guide).

Parameters parameters = new Parameters();

FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class)
    .configure(parameters
        .xml()
        .setFileName("mahfile.xml")
        .setExpressionEngine(new XPathExpressionEngine()));

builder.setAutoSave(true);

try {
  configuration = builder.getConfiguration();
} catch (ConfigurationException e) {
  return;
}

configuration.getList("omg/sites[site[name='qwer2']]")

Unluckily I am getting an empty list (and can't check the size of it (in order to check how many sites are inside)) so the query seems to fail. What am I doing wrong?

I also tried omg/sites/site[name='qwer2'] which works with this xpath exerciser but not in my code, I'm still getting an empty list.


Solution

  • Well, after extensive doc reading and playing around I found that that's the best way to count the elements and tell whether my xml node already exists. configurationsAt() return xml nodes, which are called 'hierarchical configuration objects' in this case.

    configuration.configurationsAt("//site[name = 'qwer2']").size()