【发布时间】: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>
我正在尝试查询名称为qwer2 的site,以检查它是否已存在于文件中。我该怎么做?
这是我在 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"])>0(返回true)这样的XPath表达式来检查元素的存在可能更容易。 -
XPathFactory是 Apache Commons 配置的一部分吗? -
很遗憾没有。很高兴您找到了解决方案!
标签: java xpath apache-commons-config