如何在jsoup中获取元素的第一级子元素

use*_*220 8 java jsoup

在jsoup中Element.children()返回Element的所有子项(后代).但是,我想要Element的一级孩子(直接孩子).

我可以使用哪种方法?

Vit*_*aly 12

Element.children()仅返回直接子项.既然你把它们绑在树上,它们也有孩子.

如果您需要没有底层树结构的直接子元素,则需要按如下方式创建它们

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);
}
Run Code Online (Sandbox Code Playgroud)

产量

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>
Run Code Online (Sandbox Code Playgroud)