user1777220 user1777220 - 7 months ago 70
Java Question

How to get first-level children of an element in jsoup

In jsoup ELEMENT.children() returns all children (descendants) of ELEMENT. But, I want the ELEMENT's first-level children (direct children).
Which method can I use?

Answer

Element.children() returns direct children only. Since you get them bound to a tree, they have children too.

If you need the direct children elements without the underlying tree structure then you need to create them as follows

public static void main(String... args) {

    Document document = Jsoup
            .parse("<div><ul><li>11</li><li>22</li></ul><p>ppp<span>sp</span</p></div>");

    Element div = document.select("div").first();
    Elements divChildren = div.children();

    Elements detachedDivChildren = new Elements();
    for (Element elem : divChildren) {
        Element detachedChild = new Element(Tag.valueOf(elem.tagName()),
                elem.baseUri(), elem.attributes().clone());
        detachedDivChildren.add(detachedChild);
    }

    System.out.println(divChildren.size());
    for (Element elem : divChildren) {
        System.out.println(elem.tagName());
    }

    System.out.println("\ndivChildren content: \n" + divChildren);

    System.out.println("\ndetachedDivChildren content: \n"
            + detachedDivChildren);
}

Output

2
ul
p

divChildren content: 
<ul>
 <li>11</li>
 <li>22</li>
</ul>
<p>ppp<span>sp</span></p>

detachedDivChildren content: 
<ul></ul>
<p></p>
Comments