且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用java从xml(DOM)的多级别标签中读取特定元素

更新时间:2023-11-13 18:18:58

使用XPATH API

Use XPATH APIs

您创建一个XPathFactory:

You create an XPathFactory:

XPathFactory factory = XPathFactory.newInstance();

然后,您可以使用此工厂创建XPath对象:

You then use this factory to create an XPath object:

XPath xpath = factory.newXPath();

XPath对象编译XPath表达式:

The XPath object compiles the XPath expression:

XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);

然后可以将结果转换为DOM NodeList并循环查找所有标题: / p>

You can then cast the result to a DOM NodeList and iterate through that to find all the titles:

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