今天项目中有个需求,需要对用户上传的html内容进行非法标签的过滤,一下就想到了Jsoup,但是在实际操作中,发现Jsoup过滤后head中的title、meta等标签都会消失,尝试添加白名单等各种方法无效,最后没办法,采用了一个最笨但也是最有效的解决办法:

先把html中body的内容提取出来,在进行过滤后再把它塞回到html,主要代码如下,因为跟dom4j中的document冲突,这里使用了全类名:

//过滤内容中的非法标签
org.jsoup.nodes.Document document = Jsoup.parse(html);
//只过滤body内容
org.jsoup.nodes.Document body = Jsoup.parse(document.body().html());
//自定义的标签白名单
Cleaner cleaner = new Cleaner(WhitelistFactory.createWhitelist(WhitelistFactory.EPUB20));
org.jsoup.nodes.Document bodyCleaned = cleaner.clean(body);
document.body().html(bodyCleaned.html());
String newHtml = document.html();
你可能感兴趣的内容
0条评论

selfly

交流QQ群:32261424
Owner