[英]How I can get all values from particular tag in XML?
我有file.xml
我需要用Java從<command>
標記中提取所有值:
<?xml version="1.0"?>
<config>
<command> com1 </command>
<result> res1 </result>
<command> com2 </command>
<result> res2 </result>
</config>
可能存在一些將該值提取到ArrayList的方法嗎?
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());
}
使用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()");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.