【问题标题】:Apache commons config ignores outermost XML tag? Why? Am I doing something wrong?Apache commons 配置忽略最外层的 XML 标记?为什么?难道我做错了什么?
【发布时间】:2023-03-13 12:15:01
【问题描述】:

好的,几年前我曾经使用过 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 表达式中忽略最外面的标记。

这是为什么呢?这是设计使然吗?我做错了什么吗?

【问题讨论】:

    标签: xml apache-commons-config


    【解决方案1】:

    你是对的。在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>
    

    以及下面的确认根被忽略:

    构造键时忽略根元素。在示例中,您 不要写gui-definition.color.text,而只写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");
    

    【讨论】:

    • 谢谢,我很感激 - 我太着急了,没有仔细阅读该教程。但是,现在很清楚了。我认为仍然有点违反直觉,但只要它是一致的,我就很高兴!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2019-08-16
    • 1970-01-01
    • 2020-01-09
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多