Java 如何使用ApacheCommons解析xml中的配置文件?

Java 如何使用ApacheCommons解析xml中的配置文件?,java,xml,xml-parsing,apache-commons,Java,Xml,Xml Parsing,Apache Commons,我正在使用ApacheCommonsConfiguration 1.10来管理xml配置。这是xml格式的配置文件 <?xml version="1.0" encoding="ISO-8859-1" ?> <config> <mainServerHostname>MainServer</mainServerHostname> <failoverServers> <server>

我正在使用ApacheCommonsConfiguration 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>
这是我写的代码片段

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);
        }
    }

}

有谁能帮助我如何获得所需的输出吗?

如果您对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);
        }
    }
}
或者您可以使用一个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;
          }

        }
    }

}
import java.io.FileInputStream;
导入java.util.ArrayList;
导入java.util.List;
导入javax.xml.stream.XMLInputFactory;
导入javax.xml.stream.XMLStreamConstants;
导入javax.xml.stream.XMLStreamReader;
导入org.apache.commons.lang3.StringUtils;
公共类配置分析器{
公共静态void main(字符串[]args)引发异常{
StringBuilder内容=null;
List parents=new ArrayList();
XMLInputFactory=XMLInputFactory.newInstance();
XMLStreamReader读取器=
createXMLStreamReader(新文件输入流(“prop.xml”);
while(reader.hasNext()){
int event=reader.next();
开关(事件){
案例XMLStreamConstants.START_元素:
内容=新的StringBuilder();
if(!“config”.equalsIgnoreCase(reader.getLocalName())){
add(reader.getLocalName());
}
打破
大小写XMLStreamConstants.CHARACTERS:
如果(内容!=null){
append(reader.getText().trim());
}
打破
案例XMLStreamConstants.END_元素:
如果(内容!=null){
System.out.println(StringUtils.join(parents,'..')+“=”+content.toString());
}
remove(reader.getLocalName());
内容=空;
打破
案例XMLStreamConstants.START_文档:
打破
}
}
}
}

您首先使用的是哪个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);
        }
    }
}
mainServerHostname=MainServer
failoverServers.server.ipAddress=192.168.0.5
failoverServers.server.ipAddress=192.168.0.6
failoverServers.server.priority=1
failoverServers.server.priority=2
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;
          }

        }
    }

}