如何使用Jsoup从html元素中删除所有内联样式和其他属性(class,onclick)?
示例输入:
<div style="padding-top:25px;" onclick="javascript:alert('hi');">
This is a sample div <span class='sampleclass'> This is a sample span </span>
</div>
示例输出:
<div>This is a sample div <span> This is a sample span </span> </div>
我的代码(这是正确的方式还是其他更好的方法?)
Document doc = Jsoup.parse(html);
Elements el = doc.getAllElements();
for (Element e : el) {
Attributes at = e.attributes();
for (Attribute a : at) {
e.removeAttr(a.getKey());
}
}
答案 0 :(得分:8)
是的,确实有一种方法是迭代元素并调用removeAttr();
使用jsoup的另一种方法是使用Whitelist
类(请参阅docs),它可以与Jsoup.clean()
函数一起使用,以删除任何未指定的标记或属性来自该文件。
例如:
String html = "<html><head></head><body><div style='padding-top:25px;' onclick='javascript.alert('hi');'>This is a sample div <span class='sampleclass'>This is a simple span</span></div></body></html>";
Whitelist wl = Whitelist.simpleText();
wl.addTags("div", "span"); // add additional tags here as necessary
String clean = Jsoup.clean(html, wl);
System.out.println(clean);
将导致以下输出:
11-05 19:56:39.302: I/System.out(414): <div>
11-05 19:56:39.302: I/System.out(414): This is a sample div
11-05 19:56:39.302: I/System.out(414): <span>This is a simple span</span>
11-05 19:56:39.302: I/System.out(414): </div>