OGeek|极客世界-中国程序员成长平台

标题: java - 如何使用 Jsoup 从 html 元素中删除所有内联样式和其他属性? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-9 06:51
标题: java - 如何使用 Jsoup 从 html 元素中删除所有内联样式和其他属性?

如何使用 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());    
    }
}



Best Answer-推荐答案


是的,一种方法确实是遍历元素并调用 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>

关于java - 如何使用 Jsoup 从 html 元素中删除所有内联样式和其他属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19784051/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4