JSoup - Select all comments
I want to select all comments from开发者_JAVA百科 a document using JSoup. I would like to do something like this:
for(Element e : doc.select("comment")) {
System.out.println(e);
}
I have tried this:
for (Element e : doc.getAllElements()) {
if (e instanceof Comment) {
}
}
But the following error occurs in eclipse "Incompatible conditional operand types Element and Comment".
Cheers,
Pete
Since Comment extends Node
you need to apply instanceof
to the node objects, not the elements, like this:
for(Element e : doc.getAllElements()){
for(Node n: e.childNodes()){
if(n instanceof Comment){
System.out.println(n);
}
}
}
In Kotlin you can get via Jsoup every Comment
of the whole Document
or a specific Element
with:
fun Element.getAllComments(): List<Comment> {
return this.allElements.flatMap { element ->
element.childNodes().filterIsInstance<Comment>()
}
}
精彩评论