【发布时间】:2011-09-26 04:51:51
【问题描述】:
如何通过给定 org.w3c.dom.document 上的 xpath 字符串快速定位元素/元素?似乎没有FindElementsByXpath() 方法。例如
/html/body/p/div[3]/a
我发现当有很多同名元素时,递归遍历所有子节点级别会非常慢。有什么建议吗?
我不能使用任何解析器或库,只能使用 w3c dom 文档。
【问题讨论】:
如何通过给定 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 文件:
<html>
<head>
</head>
<body>
<p>
<div></div>
<div></div>
<div><a>link</a></div>
</p>
</body>
</html>
【讨论】:
doc 属于 org.w3c.dom.Document 类型。如果您已经有Document 的实例,只需使用我的代码的最后两行即可! P.S.:为什么投反对票?
XPathConstants.NODESET 参数的介绍) - 现在它返回 NodeList。还请查看其他常量。