如何使用Jsoup搜索评论("<! - - >")?

87e*_*ent 12 java jsoup

我想从源HTML中删除这些标签及其内容.

dla*_*lin 35

当搜索你基本上使用的Elements.select(selector)地方selector被定义这个API.但是注释在技术上不是元素,因此您可能会在这里感到困惑,它们仍然是由节点名称标识的节点#comment.

让我们看看它是如何工作的:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;

public class RemoveComments {
    public static void main(String... args) {
        String h = "<html><head></head><body>" +
          "<div><!-- foo --><p>bar<!-- baz --></div><!--qux--></body></html>";
        Document doc = Jsoup.parse(h);
        removeComments(doc);
        doc.html(System.out);
    }

    private static void removeComments(Node node) {
        for (int i = 0; i < node.childNodeSize();) {
            Node child = node.childNode(i);
            if (child.nodeName().equals("#comment"))
                child.remove();
            else {
                removeComments(child);
                i++;
            }
        }
    }        
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你能得到一个6岁的Jsoup版本,它就可以了.否则,如果更新了api,我欢迎修复此更新的示例.看起来childNodes列表<node>在某些版本中是不可修改的. (2认同)