如何使用apache commons解析xml中的配置文件?

时间:2015-02-11 14:00:28

标签: java xml xml-parsing apache-commons

我正在使用apache commons配置1.10来管理xml配置。这是xml格式的配置文件。

<?xml version="1.0" encoding="ISO-8859-1" ?>
<config>
    <mainServerHostname>MainServer</mainServerHostname>
    <failoverServers>
        <server>
            <ipAddress>192.168.0.5</ipAddress>
            <priority>1</priority>
        </server>
        <server>
            <ipAddress>192.168.0.6</ipAddress>
            <priority>2</priority>
        </server>
    </failoverServers>
</config>

我需要打印以下内容

mainServerHostname=MainServer
failoverServers.server.ipAddress=192.168.0.5
failoverServers.server.priority=1
failoverServers.server.ipAddress=192.168.0.6
failoverServers.server.ipAddress=2

这是我写的代码片段

public void loadXmlFile(String filename) {
    XMLConfiguration config = null;
    try {
        config = new XMLConfiguration(filename);
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    List<HierarchicalConfiguration> fields= config. configurationsAt("failoverServers");
    for (Iterator it = fields.iterator(); it.hasNext();) {
        HierarchicalConfiguration sub = (HierarchicalConfiguration) it
                .next();
        Iterator<String> keyIter = sub.getKeys();
        String key, value;
        while (keyIter.hasNext()) {
            key = keyIter.next();
            value = sub.getString(key);
            System.out.println("Key:: " + key + " Val:: " + value);
        }
    }

}

这是运行上述代码后的结果。因为,我无法遍历整个xml树结构。

Key:: server.ipAddress Val:: 192.168.0.5
Key:: server.priority Val:: 1

有人可以帮助我如何获得所需的输出吗?

1 个答案:

答案 0 :(得分:2)

如果您特别关注apache commons配置,您可以这样做

public void loadXmlFile(String filename) {
    XMLConfiguration config = null;
    try {
        config = new XMLConfiguration(filename);
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    Iterator<String> keyIter = config.getKeys();
    String key;
    while (keyIter.hasNext()) {
        key = keyIter.next();
        Object prop = config.getProperty(key);
        if(prop instanceof Collection) {
                List<String> values = (List<String>) prop;
                for(String value : values){
                    System.out.println(key + "=" + value);
                }
        } else {
            System.out.println(key + "=" + prop);
        }
    }
}

对于上面的xml,这将打印

mainServerHostname=MainServer
failoverServers.server.ipAddress=192.168.0.5
failoverServers.server.ipAddress=192.168.0.6
failoverServers.server.priority=1
failoverServers.server.priority=2

或者您可以使用StAX解析器来实现此目的。

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

import org.apache.commons.lang3.StringUtils;


public class ConfigParser {

    public static void main(String[] args) throws Exception {
        StringBuilder content = null;
        List<String> parents = new ArrayList<>();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = 
        factory.createXMLStreamReader(new FileInputStream("prop.xml"));

        while(reader.hasNext()){
          int event = reader.next();

          switch(event){
        case XMLStreamConstants.START_ELEMENT: 
            content = new StringBuilder();
            if(!"config".equalsIgnoreCase(reader.getLocalName())) {
                parents.add(reader.getLocalName());
            }
            break;

        case XMLStreamConstants.CHARACTERS:
            if (content != null) {
                    content.append(reader.getText().trim());
                }
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (content != null) {
                    System.out.println(StringUtils.join(parents, '.') + "=" + content.toString());
                }
            parents.remove(reader.getLocalName());
                content = null;
                break;

        case XMLStreamConstants.START_DOCUMENT:
          break;
          }

        }
    }

}