Reputation: 1001
I have a HTML/JSP's DOM with me, I want to search a particular text inside a DOM and need to build the XPath for the element which contains the text. Using Jsoup API.Building a xpath is working fine
I am able to search the text if it is a value of the element or the value of the attributes of the element. Suppose if a text is there in the DOM without any tags , and if text is contained in span nodes, how do I can search?
Upvotes: 1
Views: 1270
Reputation: 4891
There are a few different solutions.
The jsoup API has a Selector class that implements pseudo-selectors. Specifically:
:contains(text)
:matches(regex)
These will return a list of elements that contain the search text. You'll have to try it to see if they return the parent container or the exact child, or some combination.
The Element class has a few methods that may prove useful:
These methods allow retrieval of elements or parent elements that contain a given text or regex pattern.
This has the disadvantage that if the string you want to match is the same as the value for an attribute or the value for a node name, it will return false positives.
See the String API; useful functions might be indexOf
and split
.
See the Pattern API for constructing regular expressions.
Upvotes: 2