【问题标题】:How to uncomment html tags using jsoup如何使用jsoup取消注释html标签
【发布时间】:2014-01-11 21:30:06
【问题描述】:

我想知道是否可以使用 jsoup 取消注释 html 标签,例如更改:

<!--<p> foo bar </p>-->

<p> foo bar </p>

【问题讨论】:

    标签: java html dom tags jsoup


    【解决方案1】:

    是的,这是可能的。这是解决此问题的一种方法:

    1. 查找所有评论节点
    2. 为每条评论提取数据属性
    3. 在当前评论节点之后插入一个包含数据的新节点
    4. 删除评论节点

    看看这段代码:

     public class UncommentComments {
            public static void main(String... args) {
                String htmlIn = "<html><head></head><body>"
                        + "<!--<div> hello there </div>-->"
                        + "<div>not a comment</div>"
                        + "<!-- <h5>another comment</h5> -->" 
                        + "</body></html>";
                Document doc = Jsoup.parse(htmlIn);
                List<Comment> comments = findAllComments(doc);
                for (Comment comment : comments) {
                    String data = comment.getData();
                    comment.after(data);
                    comment.remove();
                }
                 System.out.println(doc.toString());
            }
    
            public static List<Comment> findAllComments(Document doc) {
                List<Comment> comments = new ArrayList<>();
                for (Element element : doc.getAllElements()) {
                    for (Node n : element.childNodes()) {
                        if (n.nodeName().equals("#comment")){
                            comments.add((Comment)n);
                        }
                    }
                }
                return Collections.unmodifiableList(comments);
            }
        }
    

    鉴于此 html 文档:

    <html>
      <head></head>
      <body>
        <!--<div> hello there </div>-->
        <div>not a comment</div>
        <!-- <h5>another comment</h5> --> 
      </body>
    </html>
    

    将产生以下输出:

    <html>
      <head></head>
      <body>
        <div>hello there</div>
        <div>not a comment</div> 
        <h5>another comment</h5> 
      </body>
    </html>
    

    【讨论】:

    • 评论类,这是关键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2013-11-23
    • 2011-04-14
    • 1970-01-01
    • 2017-02-24
    • 2015-12-19
    相关资源
    最近更新 更多