本文介绍了如何使用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.

推荐答案

只需使用 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

这篇关于如何使用apache commons配置(java)加载xml文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:32