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

bgibtngc  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(369)

这是我的java项目结构

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

我想使用apache公共配置库加载以下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键和值加载到一个用“.”(点)分隔的层次结构节点的Map中。如果有人能在这方面帮助我,那将非常有帮助。

yrdbyhpb

yrdbyhpb1#

将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}

gwo2fgha

gwo2fgha2#

就用这个 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

相关问题