问题
I've used jsoup in the past and I can't seem to understand how the jquery like selectors are being defined. I've read the source code and I still can't understand.
public static final class ContainsOwnText extends Evaluator {
private String searchText;
public ContainsOwnText(String searchText) {
this.searchText = searchText.toLowerCase();
}
@Override
public boolean matches(Element root, Element element) {
return (element.ownText().toLowerCase().contains(searchText));
}
@Override
public String toString() {
return String.format(":containsOwn(%s", searchText);
}
}
The above can be called like this
select("*:containsOwn("+ str + ")");
Here is the select
Questions:
Can someone explain to me how the ContainsOwn works?
return String.format(":containsOwn(%s", searchText);
Why the above is not like this?
return String.format(":containsOwn(%s)", searchText);
And here is the evaluator
I'm asking because I want to understand how jsoup works, it's not I'm having a trouble making it work. I just want to know how it's done. If I wanted to replicate this behavior with the jquery-like selectors and wanted to develop something similar what should I do?
回答1:
When you call select(query) that query is parsed to populate a set of evaluators, which are then passed to the Collector to construct a set of elements that satisfy the query.
In this case the QueryParser on line 162 the containsOwn operation causes the contains method on line 325 to be called, which creates an instance of ContainsOwn evaluator.
This evaluator is passed to the Collector that traverses the tree calling the matches method of each evaluator. In this case (in ContainsOwn) the matches method uses the contains method of java.lang.String to check if the given string is contained within the own text of the element.
The toString method in ContainsOwn has been written to mirror the syntax used to create it and has no effect on how it is created (this is dealt with by the QueryParser). The lack of a closed parenthesis looks like a harmless typo.
来源:https://stackoverflow.com/questions/17335386/how-does-jsoup-make-jquery-like-selectors