如何从XML中的特定标记中获取所有值?

时间:2014-02-24 09:58:53

标签: java xml

我有file.xml我需要使用java <command>标记提取所有值:

<?xml version="1.0"?>
<config>
<command> com1 </command>
<result> res1 </result>
<command> com2 </command>
<result> res2 </result>
</config>

可能存在一些将此值提取到ArrayList的方法吗?

4 个答案:

答案 0 :(得分:1)

stackoverflow上有一个简单的xml解析器主题:Stack link

我鼓励您查看本教程:Xml parsing tut

答案 1 :(得分:1)

XPATH是个不错的选择。请检查下面的代码,它可以帮助你

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder =  factory.newDocumentBuilder();
    Document doc = builder.parse("test.xml");

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    XPathExpression  expr = xpath.compile("//command/text()");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    for (int i=0; i<nodes.getLength();i++){
      System.out.println(nodes.item(i).getNodeValue());
    }

答案 2 :(得分:1)

使用simple-xml

Config.java

import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class Config {

    @ElementList(entry = "result", inline = true)
    List<String> results;
    @ElementList(entry = "command", inline = true)
    List<String> commands;

    public List<String> getResults() {
        return results;
    }

    public void setResults(List<String> results) {
        this.results = results;
    }

    public List<String> getCommands() {
        return commands;
    }

    public void setCommands(List<String> commands) {
        this.commands = commands;
    }

}

App.java

import java.io.InputStream;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class App {

    public static void main(String[] args) throws Exception {
        InputStream is = App.class.getResourceAsStream("config.xml");

        Serializer serializer = new Persister();
        Config config = serializer.read(Config.class, is);

        for (String command : config.getCommands()) {
            System.out.println("command=" + command);
        }
    }
}

答案 3 :(得分:1)

您可以查看Xsylum

List<String> values = Xsylum.documentFor(xmlFile).values("//command/text()");