使用纯CSS选择器语法而不是方法调用选择下一个兄弟的方法是什么?
e.g。给出:
<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 :(得分:1)
您可以将直接replace the current DateTimeValueRetriever
with your enhanced one与sibling selector element + directSibling
注意:由于您使用的是jsoup,我包括wildcard selector *
即使您请求:&#34;不是方法调用&#34;。
示例代码
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>