2016-11-11 182 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> 
相关问题