我有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());
}
关于java - 如何从 XML 中的特定标记获取所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21984304/