如何使用apache commons配置(java)加载xml文件?
作者:互联网
这是我的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键和值加载到一个地图中,层次结构节点由“.”(点)分隔.如果有人能在这方面帮助我,那将会非常有帮助.
解决方法:
将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;
}
OUTPUT:
{favoriteSeason = summer,favoriteFruit = pomegranate,favoriteDay = today}
标签:java,xml,apache-commons 来源: https://codeday.me/bug/20191008/1873125.html