IT TIP

자바 : org.w3c.dom.document에서 xpath 문자열을 통해 요소를 찾는 방법

itqueen 2021. 1. 7. 20:15
반응형

자바 : org.w3c.dom.document에서 xpath 문자열을 통해 요소를 찾는 방법


주어진 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>

참조 URL : https://stackoverflow.com/questions/6538883/java-how-to-locate-an-element-via-xpath-string-on-org-w3c-dom-document

반응형