Reputation: 11251
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?
Upvotes: 0
Views: 473
Reputation:
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);
}
}
}
Upvotes: 1
Reputation: 1445
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());
}
Upvotes: 1
Reputation: 3694
There is a simple xml parser topic on stackoverflow : Stack link
And I would encourage you to look at this tutorial : Xml parsing tut
Upvotes: 1