문제

I'm iterating through a list of elements using jsoup, but periodically need to find one element that doesn't occur directly after the current element.

For example, if I'm iterating through and come to an img tag, I want to find the very next a tag occurring after that img tag. But, there could be a few tags in between the two.

Here's some example code:

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
}

I thought something like e.select("img ~ a") should work, but it returns no results.

What's a good way of doing this in jsoup?

도움이 되었습니까?

해결책

This appears to be a way of accomplishing the stated goal. Not sure it's the most efficient, but it is the most straightforward.

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

I was hoping for a way to run the equivalent of e.nextElementSibling("a"). Perhaps something for me to contribute back to jsoup ;-)

다른 팁

Use the nextElementSibling() method.

Inside your if statement add the following code:

Element imgNext = e.nextElementSibling();
do {
    Element a = imgNext.select("a[href]").first();         
} while (imgNext!=null && a==null);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top