简体   繁体   中英

How to get the nth previous or next element in Jsoup

Is there is anyway to get the nth previous or next specific HTML element that could possibly be on a different nesting level using jsoup?

HTML example:

 <div style="position: relative;"> <div class="wmd-container"> <div id="wmd-button-bar-42" class="wmd-button-bar"></div> <input id="previousInput" name="communitymode" type="checkbox"> </div> </div> <div class="fl" style="margin-top: 8px; height: 24px;">&nbsp;</div> <div id="draft-saved-42" class="draft-saved community-option fl" style="margin-top: 8px; height: 24px; display: none;">draft saved </div> <div id="draft-discarded-42">draft discarded</div> <div class="community-option g-row ai-center f-checkbox"> <div class="g-col -input"> <input id="NextInput" name="communitymode"> </div> <div class="g-col"> <label for="communitymode-42">community wiki</label> </div> </div> 

For example in below HTML I am pointing the element:

 <div id="draft-discarded-42">draft discarded</div> 

by using below code.

Element elem = doc.select("div[id=draft-discarded-42]").first();

I want the first previous input element:

 <input id="previousInput" name="communitymode" type="checkbox"> 

And the second previous div :

 <div class="fl" style="margin-top: 8px; height: 24px;">&nbsp;</div> 

And the second next div :

 <div class="g-col -input"> <input id="NextInput" name="communitymode"> </div> 

Unless you don't know the id attribute's value or any attribute that you can use to identify an element , you should use the selector syntax to get the element you want.

However, if you have a vague idea/don't know about the element's attributes, but know its occurrence relating to the pointed element, you can use these functions:

Nth previous occurrence of an element matching the query:

public static Element selectNthElementBefore(Element origin, String query, int count) {
    Element currentElement = origin;
    Evaluator evaluator = QueryParser.parse(query);
    while ((currentElement = currentElement.previousElementSibling()) != null) {
        int val = 0;
        if (currentElement.is(evaluator)) {
            if (--count == 0) {
                return currentElement;
            }
            val++;
        }
        Elements elems = currentElement.select(query);
        if (elems.size() > val) {
            int childCount = elems.size() - val;
            int diff = count - childCount;

            if (diff == 0) {
                Element prevElement = elems.first();
                currentElement = prevElement.children().select(query).first();
                while (currentElement != prevElement) {
                    if (currentElement == null) {
                        return prevElement;
                    }
                    prevElement = currentElement;
                    currentElement = currentElement.children().select(query).first();
                }
            }
            if (diff > 0) {
                count -= childCount;
            }
            if (diff < 0) {
                return elems.get(childCount - count);
            }
        }
    }

    if (origin.parent() != null && currentElement == null) {
        if (origin.parent().is(evaluator)) {
            if (--count == 0) {
                return origin.parent();
            }
        }
        return selectNthElementBefore(origin.parent(), query, count);
    }
    return currentElement;
}

Nth next occurrence of an element matching the query:

public static Element selectNthElementAfter(Element origin, String query, int count) {
    Element currentElement = origin;
    Evaluator evaluator = QueryParser.parse(query);
    while ((currentElement = currentElement.nextElementSibling()) != null) {
        int val = 0;
        if (currentElement.is(evaluator)) {
            if (--count == 0)
                return currentElement;
            val++;
        }
        Elements elems = currentElement.select(query);
        if (elems.size() > val) {
            int childCount = elems.size() - val;
            int diff = count - childCount;

            if (diff == 0) {
                return elems.last();
            }
            if (diff > 0) {
                count -= childCount;
            }
            if (diff < 0) {
                return elems.get(childCount + diff);
            }
        }
    }
    if (origin.parent() != null && currentElement == null) {
        return selectNthElementAfter(origin.parent(), query, count);
    }
    return currentElement;
}

Usage:

Element elem = doc.getElementById("draft-discarded-42");

Element firstPrevInput = selectNthElementBefore(elem, "input", 1);
Element secPrevDiv = selectNthElementBefore(elem, "div", 2);
Element secNextDiv = selectNthElementAfter(elem, "div", 2);

System.out.println("#### First previous input ####");
System.out.println(firstPrevInput.toString());
System.out.println("##############################\n"); 
System.out.println("#### Second previous div ####");
System.out.println(secPrevDiv.toString());
System.out.println("#############################\n");
System.out.println("#### Second next div ####");
System.out.println(secNextDiv.toString());
System.out.println("#########################");

Output:

#### First previous input ####
<input id="previousInput" name="communitymode" type="checkbox">
##############################

#### Second previous div ####
<div class="fl" style="margin-top: 8px; height: 24px;">
 &nbsp;
</div>
#############################

#### Second next div ####
<div class="g-col -input"> 
    <input id="NextInput" name="communitymode"> 
</div>
#########################

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM