JSoup - Select all comments

梦想与她 提交于 2019-11-30 20:53:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!