Whitelist类
一、类结构
org.jsoup.safety.Whitelist
public class Whitelist
extends
Whitelist类定义了一些可以被保留的标签和属性,不属于这个范围的标签和属性的都要被删除。
默认的配置方法有:
none()
simpleText()
basic()
basicWithImages()
relaxed()
如果想扩大筛选范围,可以使用以下方法:
addTags(java.lang.String...)
addAttributes(java.lang.String,java.lang.String...)
addEnforcedAttribute(java.lang.String,java.lang.String, java.lang.String)
addProtocols(java.lang.String,java.lang.String, java.lang.String...)
二、方法
Constructor Summary
()创建一个空白的Whitelist
Method Summary
给标签添加属性。Tag是属性名,keys对应的是一个个属性值。例如:addAttributes("a", "href", "class")表示:给标签a添加href和class属性,即允许标签a包含href和class属性。如果想给每一个标签添加一组属性,使用:all。例如:addAttributes(":all", "class").即给每个标签添加class属性。
给标签添加强制性属性,如果标签已经存在了要添加的属性,则覆盖原有值。tag:标签;key:标签的键;value:标签的键对应的值。例如:addEnforcedAttribute("a", "rel", "nofollow")表示
(String tag, String key, String... protocols)给URL属性添加协议。例如:addProtocols("a", "href", "ftp", "http", "https")标签a的href键可以指向的协议有ftp、http、https
addTags(String... tags)向Whitelist添加标签
()允许的标签包括:a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li, ol, p, pre, q, small, strike, strong, sub, sup, u, ul,以及合适的属性。标签a指向的连接可以是http, https, ftp, mailto,转换完后会强制添加rel=nofollow这个属性。不允许包含图片。
在basic的基础上增加了图片的标签:img以及使用src指向http或https类型的图片链接。
protected boolean
判断参数tag是否符合当前的Whitelist
()只保留文本,其他所有的html内容均被删除
(boolean preserve)false(默认):不保留相对地址的url;true:保留相对地址的url
()允许的标签:a, b, blockquote, br, caption, cite, code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, u, ul。结果不包含标签rel=nofollow,如果需要可以手动添加。
()只允许:b, em, i, strong, u.
三、总结
Whitelist的基本方法有四种:
none:只保留了文本;
simpleText:简单的文本属性b, em, i, strong, u。
basic:a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li, ol, p, pre, q,small,strike, strong, sub, sup, u, ul。
basicWithImages:a, b, blockquote, br, cite, code, dd, dl,dt, em, i, li, ol, p, pre, q, small, strike, strong, sub, sup, u, ul、img、src。
Relaxed:a, b, blockquote,br, caption, cite, code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, h5, h6,i, img, li, ol, p, pre, q, small, strike, strong, sub, sup, table, tbody, td,tfoot, th, thead, tr, u, ul。
四、实例
publicstaticvoidJsoupClean(){
html = "搜索设置";
String doc = Jsoup.clean(html, baseUri, Whitelist.none());
System.out.println(doc);
System.out.println("*******");
doc = Jsoup.clean(html, baseUri, Whitelist.simpleText());
System.out.println(doc);
System.out.println("*******");
doc = Jsoup.clean(html, baseUri, Whitelist.basic());
System.out.println(doc);
System.out.println("*******");
doc = Jsoup.clean(html, baseUri, Whitelist.basicWithImages());
System.out.println(doc);
System.out.println("*******");
doc = Jsoup.clean(html, baseUri, Whitelist.relaxed());
System.out.println(doc);
}
本文为Eliot原创,转载请注明出处:
http://blog.csdn.net/xyw_eliot/article/details/9145523