如何使用jsoup取消注释HTML标签

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

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

为了

<p> foo bar </p>
1个回答

9

是的,这是可能的。以下是一种解决方法:

  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>

注释类,这是关键。 - Jalal Sordo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接