如何在jsoup中获取元素的第一级子元素
在jsoup中, Element.children()
返回Element的所有子项(后代)。 但是,我想要Element的一级孩子(直接孩子)。
我可以使用哪种方法?
Element.children()仅返回直接子项。 既然你把它们绑在一棵树上,它们也有孩子。
如果您需要没有底层树结构的直接子元素,则需要按如下方式创建它们
public static void main(String... args) { Document document = Jsoup .parse("- 11
- 22
pppsp
"); 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: - 11
- 22
pppsp
detachedDivChildren content:
您可以随时使用ELEMENT.child(索引)和索引,您可以选择所需的子项。
在这里,您可以获得一级孩子的价值
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()); }
这应该为您提供父节点的直接后代所需的列表:
Elements firstLevelChildElements = doc.select("parent-tag > *");
或者您也可以尝试检索父元素,通过child(int index)
获取第一个子节点,然后尝试通过siblingElements()
检索此子节点的兄弟siblingElements()
。
这将为您提供除使用的孩子之外的第一级孩子的列表,但是您必须在外部添加孩子。
Elements firstLevelChildElements = doc.child(0).siblingElements();