我想知道是否可以使用jsoup取消注释html标签,例如更改:
<!--<p> foo bar </p>-->
到
<p> foo bar </p>
答案 0 :(得分:7)
是的,这是可能的。这是解决这个问题的一种方法:
看一下这段代码:
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>