I wonder if it is possible to uncomment html tags using jsoup for instance change :
<!--<p> foo bar </p>-->
to
<p> foo bar </p>
Yes it is possible. Here is one way to solve this:
Have a look at this code:
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);
}
}
Given this html document:
<html>
<head></head>
<body>
<!--<div> hello there </div>-->
<div>not a comment</div>
<!-- <h5>another comment</h5> -->
</body>
</html>
Will result in this output:
<html>
<head></head>
<body>
<div>hello there</div>
<div>not a comment</div>
<h5>another comment</h5>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With