简体   繁体   中英

How I can get all values from particular tag in XML?

I have file.xml i need extract with java all values from <command> tag:

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

May be it exists some methods to extract this values to ArrayList?

There is a simple xml parser topic on stackoverflow : Stack link

And I would encourage you to look at this tutorial : Xml parsing tut

XPATH is a good option. Please check below code, it could help you

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

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

您可以查看Xsylum

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM