Java:如何通过org.w3c.dom.document上的xpath字符串定位元素
如何通过给定org.w3c.dom.document上的xpath字符串快速定位元素?似乎没有Java:如何通过org.w3c.dom.document上的xpath字符串定位元素,java,dom,xpath,Java,Dom,Xpath,如何通过给定org.w3c.dom.document上的xpath字符串快速定位元素?似乎没有FindElementsByXpath()方法。比如说 /html/body/p/div[3]/a 我发现当有许多同名元素时,递归遍历所有子节点级别的速度非常慢。有什么建议吗 我不能使用任何解析器或库,只能使用w3c dom文档。尝试以下方法: //obtain Document somehow, doesn't matter how DocumentBuilder b = DocumentBuild
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);
}
在我的代码示例中,
doc
属于org.w3c.dom.Document
类型。如果您已经有一个文档的实例
,只需使用我的代码的最后两行就可以了!旁白:为什么要投否决票?这会返回文本。我需要一个或多个DomeElement。请参阅我的编辑(介绍XPathConstants.NODESET
参数)-现在它返回NodeList
。还可以看看其他常量。谢谢。这是一个很好的答案。@Tomasz Nukiewicz,你能看看我的实现吗。我知道我不是发问者,伊茨提出了一个不同的问题,但我从你的回答中得到了参考,所以我希望你能帮助我,
<html>
<head>
</head>
<body>
<p>
<div></div>
<div></div>
<div><a>link</a></div>
</p>
</body>
</html>