2013-05-06 65 views
2

有沒有一種有效的方法來檢查給定的元素是否匹配選擇器,比如jQuery中的is()方法(http://api.jquery.com/is/)?有沒有一種有效的方法來測試一個元素是否與Jsoup中的選擇器匹配?

我發現這個解決辦法,但我認爲它有糟糕的表現:

public static String cleanSelector(String selector) { 
    return selector.replaceAll(":link|:active|:visited|:hover|:after|:focus", ""); 
} 

public static boolean elementIs(Element elem, String selector, Element root) { 
    Elements elems = root.select(cleanSelector(selector)); 
    return elems.contains(elem); 
} 

回答

0

使用包私人QueryParser類:

Evaluator eval = QueryParser.parse(query); 
boolean result = eval.matches(element.ownerDocument(), element); 
+0

我還希望評論關於這個答案如何能沒有劫持到私人Jsop包中使用......否則它似乎是無用的。 – 2016-01-05 21:53:30

+1

@XtraCoder現在有'is(String cssSelector)'方法,它正是這樣做的。但它尚未在最新版本中發佈,但已在[此次提交]中(https://github.com/jhy/jsoup/commit/4f707008353e272c12a7a6543d6ecfc666a7cc64)。 – stipx 2016-12-27 19:45:38

相關問題