java - 如何在 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>
我正在尝试查询site
with 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 练习器但不在我的代码中,我仍然得到一个空列表。
解决方案
好吧,经过大量的文档阅读和玩耍后,我发现这是计算元素并判断我的 xml 节点是否已经存在的最佳方法。configurationsAt()
返回 xml 节点,在这种情况下称为“分层配置对象”。
configuration.configurationsAt("//site[name = 'qwer2']").size()
推荐阅读
- nginx - 托管在 nginx 上的 .net core 3.1 web api 适用于 http POST,但不适用于 HTTPS
- pandas - 有没有办法用我已经制作的图创建图表网格?
- flutter - 如何让 Paypal 在 Flutter 应用内付款
- mysql - #1241 - 操作数应包含 1 列嵌套查询
- android-studio - Android Studio中黄色和斜体的方法名称是什么意思?
- javascript - 节点 Javascript 类 ReferenceError: X 未定义
- r - GGPLOT2中的字幕
- git - git add 和 git commit 混淆
- javascript - 为什么返回未定义?(免费代码营)
- python - 过滤文件,将文件中的值移动到列表