2011-06-30 27 views
51

与えられたorg.w3c.dom.documentのxpath文字列を使って要素/要素をすばやく見つける方法を教えてください。 FindElementsByXpath()メソッドがないようです。例Java:org.w3c.dom.documentのxpath文字列を使って要素を見つける方法

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

のために私は、同じ名前の要素が多い時に再帰的にすべての子ノードのレベルを反復処理が非常に遅いことがことがわかりました。助言がありますか?

パーサまたはライブラリを使用できません。w3c domドキュメントのみで動作する必要があります。

+0

https://stackoverflow.com/questions/45495758/detect-hyperlink-hover-in-webview-and-:以下page.htmlファイルで

//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); } 

をprint-the-link – Sedrick

答えて

85

これを試してみてください:

<html> 
    <head> 
    </head> 
    <body> 
    <p> 
    <div></div> 
    <div></div> 
    <div><a>link</a></div> 
    </p> 
    </body> 
</html> 
+0

私のコード例では、 'doc'は' org.w3c.dom.Document'型です。既に 'Document'のインスタンスを持っている場合は、私のコードの最後の2行を使用してください! P.S .:なぜdownvoteですか? –

+0

これはテキストを返します。私はドームメントやドームが必要です。 – KJW

+0

私の編集( 'XPathConstants.NODESET'パラメタの紹介)を見てください。今度は' NodeList'を返します。他の定数も見てください。 –

関連する問題