How to get first level children from jsoup element

In jsoup Element.children() returns all the child elements (descendants) of the element. But I want the children of the first level Element (direct children).

Which method can i use?

+6
source share
4 answers

Element.children () returns only direct children. Since you tie them to a tree, they also have children.

If you need direct children without a basic tree structure, 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> 
+9
source

You can always use ELEMENT.child (index) with an index that you can choose which child you want.

+1
source

Here you can get the meaning 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()); } 
+1
source

This should provide you with a list of direct descendants of the parent node:

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

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

This will give you a list of first-level children, excluding the child used, however you will have to add the child from the outside.

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

All Articles