好吧,几年前我曾经使用过 apache commons config,可能已经忘记了一些东西。
我对正在发生的事情感到有点困惑,这对我来说似乎违反直觉。
所以,这是我的代码:
public static void main(String[] args) throws ConfigurationException {
XMLConfiguration config = new XMLConfiguration("config/base-config.xml");
config.setExpressionEngine(new XPathExpressionEngine());
List<Object> recipients;
recipients = config.getList("emailRecipients/recipient");
System.out.println("Recipients: " + recipients.size());
for (Object recipient : recipients) {
System.out.println("\tRecipient: " + recipient);
}
}
这是我的 xml 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<emailRecipients>
<recipient>me@email.com</recipient>
<recipient>you@email.com</recipient>
</emailRecipients>
但是,我的代码不会像我预期的那样读取收件人标签。
相反,我必须修改我的配置文件,使其看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<arbitrary-outer-tag>
<emailRecipients>
<recipient>me@email.com</recipient>
<recipient>you@email.com</recipient>
</emailRecipients>
</arbitrary-outer-tag>
因此,在寻找我需要的配置项时,似乎无论最外层的标签是什么都必须在 XPath 表达式中忽略。
这是为什么呢?这是设计使然吗?我做错了什么吗?
最佳答案
你是对的。在 Apache Commons Configuration ,根据设计,在指定键时忽略根。考虑来自 Apache Commons Config User Guide 的这个例子:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<gui-definition>
<colors>
<background>#808080</background>
<text>#000000</text>
<header>#008000</header>
<link normal="#000080" visited="#800080"/>
<default>${colors.header}</default>
</colors>
<rowsPerPage>15</rowsPerPage>
<buttons>
<name>OK,Cancel,Help</name>
</buttons>
<numberFormat pattern="###\,###.##"/>
</gui-definition>
以及以下根被忽略的确认:
The root element is ignored when constructing keys. In the example you do not write gui-definition.color.text, but only color.text.
请放心,您并不是唯一对此感到疑惑的人,尤其是对于 XPath 键。但至少它是一致的。对于这个 XML 文档,
<?xml version="1.0" encoding="ISO-8859-1" ?>
<database>
<tables>
<table tableType="system">
XPaths have to ignore the root element too :
HierarchicalConfiguration config = ...
config.setExpressionEngine(new XPathExpressionEngine());
// Now we can use XPATH queries:
List<Object> fields = config.getList("tables/table[1]/fields/name");
关于xml - Apache commons 配置忽略最外层的 XML 标签?为什么?难道我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235895/