4

如何使用 Jsoup 从 html 元素中删除所有内联样式和其他属性(类、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());    
    }
}
4

1 回答 1

11

Yes, one method is indeed to iterate through the elements and call removeAttr();

An alternative method using jsoup is to make use of the Whitelist class (see docs), which can be used with the Jsoup.clean() function to remove any non-specified tags or attributes from the document.

For example:

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);

Will result in the following output:

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>
于 2013-11-05T10:00:44.503 回答