如何在Apache Commons Configuration中使用XPath按值查询XMLConfiguration?

时间:2020-05-23 00:12:18

标签: java xpath apache-commons-config

所以我有以下XML文件。

<?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>

我试图用名称site查询qwer2,以检查文件中是否已经存在该文件。我该怎么做?

这是我在Java中尝试过的方法(我有点遵循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']]")

不幸的是,我得到一个空列表(并且无法检查它的大小(以便检查其中有多少个站点)),因此查询似乎失败了。我在做什么错了?

我也尝试了omg/sites/site[name='qwer2'],它可以与this xpath exerciser一起使用,但是在我的代码中却没有,我仍然得到一个空列表。

1 个答案:

答案 0 :(得分:0)

好吧,经过大量的文档阅读和研究之后,我发现这是计算元素并判断我的xml节点是否已经存在的最佳方法。 configurationsAt()返回xml节点,在这种情况下,这些节点称为“分层配置对象”。

configuration.configurationsAt("//site[name = 'qwer2']").size()
相关问题