如何通过给定 org.w3c.dom.document 上的 xpath 字符串快速定位一个或多个元素?似乎没有FindElementsByXpath()
方法。例如
/html/body/p/div[3]/a
我发现当存在大量同名元素时,递归迭代所有子节点级别会非常慢。有什么建议么?
我无法使用任何解析器或库,只能使用 w3c dom 文档。
尝试这个:
//obtain Document somehow, doesn't matter how
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html"));
//Evaluate XPath against Document itself
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a",
doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
Element e = (Element) nodes.item(i);
}
与以下page.html
file:
<html>
<head>
</head>
<body>
<p>
<div></div>
<div></div>
<div><a>link</a></div>
</p>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)