【问题标题】:Selector for next sibling of current element当前元素下一个兄弟的选择器
【发布时间】:2019-04-08 12:38:13
【问题描述】:

使用纯 CSS 选择器语法而不是方法调用来选择下一个兄弟的方法是什么?

例如给定:

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

如果元素e 代表div,那么我需要选择&lt;whatever&gt;,无论它是&lt;div&gt; 还是&lt;p&gt; 或其他。

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

寻找这样一个选择器的原因是有一个通用方法可以从兄弟节点或子节点获取数据。

我正在尝试解析应用程序的 HTML,其中 div 的位置无法计算为选择器。否则,这就像使用一样简单:

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

我基本上想要的是从上面的选择器中删除 div.thespecificDivID 部分,(例如,如果这有效: "+div, +p" )

【问题讨论】:

标签: java css-selectors jsoup


【解决方案1】:

您可以直接使用sibling selector element + directSiblingwildcard selector * 结合使用

注意:由于您使用的是 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多