如何使用apache commons配置(java)加载xml文件?

时间:2015-01-15 09:57:21

标签: java xml apache-commons

这是我的java项目结构

src/main/java
  |_LoadXml.java
src/main/resources/
  |_config.xml
src/test/java
src/test/resources

我想使用apache-common配置库加载以下xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Here are some favorites</comment>
<entry key="favoriteSeason">summer</entry>
<entry key="favoriteFruit">pomegranate</entry>
<entry key="favoriteDay">today</entry>
</properties>

我为LoadXml.java编写了以下代码片段

public static void configure() {
    try {
       XMLConfiguration config = new XMLConfiguration("config.xml");
        node = config.getRootElementName();
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    return;
}

我想将xml密钥和值加载到一个地图中,层次结构节点由“。”(点)分隔。如果有人能在这方面帮助我,那将会非常有帮助。

2 个答案:

答案 0 :(得分:1)

将xml密钥和值加载到Map

    public static Map<String, String> parseConfig() throws ConfigurationException {

        XMLConfiguration config = new XMLConfiguration("config.xml");
        NodeList list = config.getDocument().getElementsByTagName("entry");

        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            String key = node.getAttributes().getNamedItem("key").getTextContent();
            String val = node.getTextContent();
            map.put(key, val);
        }
        System.out.println(map);
        return map;
    }

<强>输出
{favoriteSeason=summer, favoriteFruit=pomegranate, favoriteDay=today}

答案 1 :(得分:1)

只需使用config.getRootNode(),然后使用node.getChildren("entry")

XMLConfiguration config = new XMLConfiguration("_config.xml");
Map<String, String> configMap = new HashMap<String, String>();
ConfigurationNode node = config.getRootNode();
for (ConfigurationNode c : node.getChildren("entry"))
{
    String key = (String)c.getAttribute(0).getValue();
    String value = (String)c.getValue();
    configMap.put(key, value);
}

然后你可以这样做:

System.out.println(configMap.get("favoriteSeason")); // prints: summer