在jsoup中获取特定标记类型的下一个元素

时间:2014-05-11 03:43:17

标签: java jsoup

我正在使用jsoup迭代元素列表,但是需要定期找到一个不会在当前元素之后直接出现的元素。

例如,如果我正在迭代并转到img标记,我想找到在a标记之后发生的下一个img标记。但是,两者之间可能会有一些标签。

以下是一些示例代码:

for (Element e : elements) {
    if (e.tagName().equalsIgnoreCase("img")) {
        // Do some stuff with "img" tag
        // Now, find the next tag in the list with tag <a>
    }

    // Do some other things before the next loop iteration
}

我认为像e.select("img ~ a")之类的东西应该有用,但它不会返回任何结果。

在jsoup中这样做的好方法是什么?

2 个答案:

答案 0 :(得分:4)

这似乎是实现既定目标的 方式。不确定它是最有效的,但它是最直接的。

Element node = e.nextElementSibling();
while (node != null && !node.tagName().equalsIgnoreCase("a")) {
    node = node.nextElementSibling();
}

我希望有办法运行相当于e.nextElementSibling("a")的方法。或许我可以回馈jsoup; - )

答案 1 :(得分:0)

使用nextElementSibling()方法。

在if语句中添加以下代码:

Element imgNext = e.nextElementSibling();
do {
    Element a = imgNext.select("a[href]").first();         
} while (imgNext!=null && a==null);
相关问题