Reputation: 19150
I'm using Java 6. As the question states, how would I write a method that takes an org.w3c.dom.Element and an xpath string and returns a list of matching org.w3c.dom.Elements, assuming there are any?
If it helps all the Elements were obtained by parsing XHTML documents.
Edit: Per the suggestion given, I tried
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final NodeList result = (NodeList) xpath.evaluate(xpathStr, rootElement, XPathConstants.NODESET);
where my xpathStr was "//div[contains(@class,'listing')]/h3//a[1]/span/text()", however, the result is returning xpaths matching the entire parent document, and not just things in the "rootElement" Element object. I have verified that the rootElement object doesn't contain some of the results returned within its HTML.
Upvotes: 1
Views: 1495
Reputation: 27994
Here is a good article on the topic: http://www.ibm.com/developerworks/library/x-javaxpathapi/
Use XPathFactory to create an XPath, and then use xpath.evaluate("expression", contextNode, NODESET) to get the list of matching elements.
The contextNode is the "given element", and so any XPath expression evaluated from that starting point will give elements that are descendants of ("within") that element, depending on what axes they use.
Upvotes: 2