【问题标题】:How to query XMLConfiguration by value with XPath in Apache Commons Configuration?如何在 Apache Commons 配置中使用 XPath 按值查询 XMLConfiguration?
【发布时间】:2020-05-23 00:12:18
【问题描述】:

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

我正在尝试查询名称为qwer2site,以检查它是否已存在于文件中。我该怎么做?

这是我在 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 一起使用,但不在我的代码中,我仍然得到一个空列表。

【问题讨论】:

  • 使用XPathFactory(编译+评估)和像count(//name[.="qwer2"])&gt;0(返回true)这样的XPath表达式来检查元素的存在可能更容易。
  • XPathFactory 是 Apache Commons 配置的一部分吗?
  • 很遗憾没有。很高兴您找到了解决方案!

标签: java xpath apache-commons-config


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 2012-02-08
    • 2013-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多