开发者

Java: how to locate an element via xpath string on org.w3c.dom.document

开发者 https://www.devze.com 2023-03-16 07:42 出处:网络
How do you quickly locate element/elements via xpath string on a given org.w3c.dom.document? there s开发者_运维百科eems to be no FindElementsByXpath() method. For example

How do you quickly locate element/elements via xpath string on a given org.w3c.dom.document? there s开发者_运维百科eems to be no FindElementsByXpath() method. For example

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

I found that recursively iterating through all the child node levels to be quite slow when there are lot of elements of same name. Any suggestions?

I cannot use any parser or library, must work with w3c dom document only.


Try this:

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

With the following page.html file:

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

精彩评论

暂无评论...
验证码 换一张
取 消