如何使用apache commons配置(java)加载xml文件? [英] How to load xml file using apache commons configuration (java)?
本文介绍了如何使用apache commons配置(java)加载xml文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的java项目结构
This is my java project strucutre
src/main/java
|_LoadXml.java
src/main/resources/
|_config.xml
src/test/java
src/test/resources
我想使用apache-common配置库加载以下xml文件。
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>
我为LoadXml.java编写了以下代码片段
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;
}
我想将xml密钥和值加载到一个层次结构节点分隔的地图中一个。(点)。如果有人可以在这方面帮助我,那将会非常有帮助。
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.
推荐答案
只需使用配置即可。 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
这篇关于如何使用apache commons配置(java)加载xml文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文