Issue
I am working on a program that gives the user the opportunity to define his own selection string. For example in the expression:
doc.select("a[href]");
The user would have specified the "a[href]" part. Now my question is, how can I check if the passed in string is a valid JSoup selector string? Does anyone know how to validate this?
Any help would be very much appreciated.
Thanks
Solution
approach 1: Edit the Jsoup source and make the Parser public or implement your own method there
approach 2: Parse a simple dummy element and catch the exceptions. if one is thrown: query is not valid, else it's ok. Not the best solution but it works.
Here's an example:
private static final Element dummy = new Element(Tag.valueOf("p"), ""); // used for "testparsing"
// ...
public static boolean isValid(String query)
{
if( query == null ) // Check for null
return false;
try
{
Selector.select(query, dummy); // Use the querystring on the dummy - returnvalue is not relevant
}
catch( Selector.SelectorParseException | IllegalArgumentException ex ) // these exceptions are thrown if something is not ok
{
return false; // If something is not ok, the query is invalid
}
return true; // All ok, query is valid
}
Test:
System.out.println(isValid(null)); // not valid
System.out.println(isValid("div.abc")); // valid
System.out.println(isValid("p[")); // not valid
System.out.println(isValid("a:matchesxy")); // not valid
System.out.println(isValid("div > a")); // valid
Testresult:
false
true
false
false
true
Answered By - ollo
Answer Checked By - David Marino (JavaFixing Volunteer)