2016-11-11 102 views
0

什麼是純粹使用CSS選擇器語法,而不是一個方法調用選擇一個同級的方式下一個兄弟?選擇當前元素

例如給定:

<div>Foo</div><whatever>bar</whatever> 

如果元素e代表div然後我需要選擇<whatever>不論它是否是一個<div><p>或什麼的。

String selectorForNextSibling = "... "; 
Element whatever = div.select(selectorForNextSibling).get(0); 

查找這樣的選擇器的原因是有一個通用的方法,可以從兄弟節點或子節點獲取數據。

我試圖解析一個應用程序的HTML其中div位置無法計算一個選擇。否則,這將一直是那麼容易,因爲使用:

"div.thespecificDivID + div,div.thespecificDivID + p" 

我想主要是從上面選擇刪除div.thespecificDivID部分(例如,如果這個工作:「+ DIV + P」)

+0

難道這解決了嗎? http://stackoverflow.com/help/someone-answers –

回答

0

你可以結合與wildcard selector *

使用直接sibling selector element + directSibling:由於您使用jsoup,包括我,即使你要求jsoups nextElementSibling():「沒有方法調用」。

示例代碼

String html = "<div>1A</div><p>1A 1B</p><p>1A 2B</p>\r\n" + 
     "<div>2A</div><span>2A 1B</span><p>2A 2B</p>\r\n" + 
     "<div>3A</div><p>3A 1B</p>\r\n" + 
     "<p>3A 2B</p><div></div>"; 

Document doc = Jsoup.parse(html); 

String eSelector = "div"; 

System.out.println("with e.cssSelector and \" + *\""); 
// if you also need to do something with the Element e 
doc.select(eSelector).forEach(e -> { 
    Element whatever = doc.select(e.cssSelector() + " + *").first(); 
    if(whatever != null) System.out.println("\t" + whatever.toString()); 
}); 

System.out.println("with direct selector and \" + *\""); 
// if you are only interested in Element whatever 
doc.select(eSelector + " + * ").forEach(whatever -> { 
    System.out.println("\t" + whatever.toString()); 
}); 

System.out.println("with jsoups nextElementSibling"); 
//use jsoup build in function 
doc.select(eSelector).forEach(e -> { 
    Element whatever = e.nextElementSibling(); 
    if(whatever != null) System.out.println("\t" + whatever.toString()); 
}); 

輸出

with e.cssSelector and " + *" 
    <p>1A 1B</p> 
    <span>2A 1B</span> 
    <p>3A 1B</p> 
with direct selector and " + *" 
    <p>1A 1B</p> 
    <span>2A 1B</span> 
    <p>3A 1B</p> 
with jsoups nextElementSibling 
    <p>1A 1B</p> 
    <span>2A 1B</span> 
    <p>3A 1B</p>