How to load xml file using apache commons configuration (java)?

后端 未结 2 2150
一生所求
一生所求 2021-01-15 04:04

This is my java project strucutre

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

I want

2条回答
  •  广开言路
    2021-01-15 04:40

    Load xml keys and values into a 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;
        }
    

    OUTPUT:
    {favoriteSeason=summer, favoriteFruit=pomegranate, favoriteDay=today}

提交回复
热议问题