如何在jsoup中获取元素的第一级子元素 [英] How to get first-level children of an element in jsoup
本文介绍了如何在jsoup中获取元素的第一级子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在jsoup中 Element.children()
返回Element的所有子项(后代)。但是,我想要Element的一级孩子(直接孩子)。
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?
推荐答案
Element.children()仅返回直接子项。由于你将它们绑定到一棵树上,它们也有孩子。
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);
}
输出
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>
这篇关于如何在jsoup中获取元素的第一级子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文