首页 > 解决方案 > 如何在 Apache Commons 配置中使用 XPath 按值查询 XMLConfiguration?

问题描述

所以我有以下 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>

我正在尝试查询sitewith nameqwer2以检查它是否已存在于文件中。我该怎么做呢?

这是我在 Java 中尝试过的(我有点遵循本指南)。

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']了使用此 xpath 练习器但不在我的代码中,我仍然得到一个空列表。

标签: javaxpathapache-commons-config

解决方案


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

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

推荐阅读