user1777220
user1777220

Reputation: 133

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?

Upvotes: 9

Views: 32778

Answers (4)

Vasu Mangal
Vasu Mangal

Reputation: 31

This should give you the desired list of direct descendants of the parent node:

Elements firstLevelChildElements = doc.select("parent-tag > *");

OR You can also try to retrieve the parent element, get the first child node via child(int index) and then try to retrieve siblings of this child via siblingElements().

This will give you the list of first level children excluding the used child, however you'd have to add the child externally.

Elements firstLevelChildElements = doc.child(0).siblingElements();

Upvotes: 3

Zeeshan Akhter
Zeeshan Akhter

Reputation: 1891

Here you can get the value of first-level children

 Element addDetails = doc.select("div.container > div.main-content > div.clearfix > div.col_7.post-info > ul.no-bullet").first();
    Elements divChildren = addDetails.children();
    for (Element elem : divChildren) {
       System.out.println(elem.text());
                }

Upvotes: 0

Vitaly
Vitaly

Reputation: 2790

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>

Upvotes: 13

William Proulx
William Proulx

Reputation: 65

You could always use the ELEMENT.child(index) with the index you can choose which child you want.

Upvotes: 1

Related Questions