How to load xml file using apache commons configur

2019-05-21 17:45发布

This is my java project strucutre

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

I want to load the following xml file using apache-common configuration library.

<?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>

I have written the following code snippet for LoadXml.java

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

I want to load xml keys and values into a map with hierarchy nodes seperated by a "."(dot). It would be greatly helpful if someone can help me in this regard.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-05-21 18:25

Load xml keys and values into a 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;
    }

OUTPUT:
{favoriteSeason=summer, favoriteFruit=pomegranate, favoriteDay=today}

查看更多
劫难
3楼-- · 2019-05-21 18:33

Just use the config.getRootNode() and then 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);
}

Then you can just do:

System.out.println(configMap.get("favoriteSeason")); // prints: summer
查看更多
登录 后发表回答