如何使用apache commons配置(java)加载xml文件?
这是我的java项目结构
src/main/java |_LoadXml.java src/main/resources/ |_config.xml src/test/java src/test/resources
我想使用apache-common配置库加载以下xml文件。
Here are some favorites summer pomegranate today
我为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 parseConfig() throws ConfigurationException { XMLConfiguration config = new XMLConfiguration("config.xml"); NodeList list = config.getDocument().getElementsByTagName("entry"); Map map = new HashMap(); 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}
只需使用config.getRootNode()
然后使用node.getChildren("entry")
XMLConfiguration config = new XMLConfiguration("_config.xml"); Map configMap = new HashMap(); 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
- 使用Linux上的Apache Commons Compression压缩文件时编码错误
- 在GenericObjectPool中创建对象
- 使用Apache Commons CLI库时如何获取参数
- Java BeanUtilsBean:将Date转换为String
- 使用Apache Commons FTPClient监控进度
- apache-commons-config PropertiesConfiguration:丢失最后一个属性后的注释
- 使用Commons或Guava将文本文件导入Java List
- Apache commons fileupload“Streaming API”
- PropertyPlaceholderConfigurer从XML文件读取(Apache Commons配置)