问题
I want to select all comments from 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
回答1:
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);
}
}
}
回答2:
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>()
}
}
来源:https://stackoverflow.com/questions/4063263/jsoup-select-all-comments