2011-06-30 46 views
51

如何通過給定org.w3c.dom.document上的xpath字符串快速定位元素/元素?似乎沒有FindElementsByXpath()方法。例如Java:如何通過xpath在org.w3c.dom.document上查找元素

/html/body/p/div[3]/a 

我發現,遞歸遍歷所有的子節點級別的迭代是相當緩慢的時候有很多同名的元素。有什麼建議麼?

我無法使用任何解析器或庫,只能使用w3c dom文檔。

+0

https://stackoverflow.com/questions/45495758/detect-hyperlink-hover-in-webview-and- print-the-link – Sedrick

回答

85

試試這個:

//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.getDocumentElement(), 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> 
+0

在我的代碼示例中'doc'是'org.w3c.dom.Document'類型。如果你已經有了一個'Document'的實例,只需要使用我的代碼的最後兩行,就是這樣! P.S .:爲什麼downvote? –

+0

這將返回文本。我需要穹頂或穹頂。 – KJW

+0

查看我的編輯(引入'XPathConstants.NODESET'參數) - 現在它返回'NodeList'。還要看看其他常量。 –

相關問題