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


how locate element/elements via xpath string on given org.w3c.dom.document? there seems no findelementsbyxpath() method. example

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

i found recursively iterating through child node levels quite slow when there lot of elements of same name. suggestions?

i cannot use parser or library, must work 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 xpath xpath = xpathfactory.newinstance().newxpath(); nodelist nodes = (nodelist)xpath.evaluate("/html/body/p/div[3]/a",         doc.getdocumentelement(), xpathconstants.nodeset); (int = 0; < nodes.getlength(); ++i) {     element e = (element) nodes.item(i); } 

with following page.html file:

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

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -