使用Jsoup清除html时保持属性具有特定值

时间:2017-05-17 08:51:10

标签: html jsoup

我正在使用这段代码从单词中清除凌乱的html,从基本上所有内容中删除它。我想只保留文本格式标签和文本对齐

[...]
String result = null;
Document html = Jsoup.parse(rawHtml, "/");
html.select("span").unwrap();
Whitelist wl = Whitelist.simpleText();
wl.addTags("div", "span", "p"); // ”
wl.addAttributes(":all", "align");
html.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
this.editStyle(html, "[align='center']", "style", "text-align: center");
this.editStyle(html, "[align='justify']", "style", "text-align: justify");
result = Jsoup.clean(html.body().html(), wl);
return result;

private void editStyle(Document html, String selector, String attrKey, String attrVal) {
    Elements values = html.select(selector);
    values.attr(attrKey, attrVal);
}

我知道同时拥有对齐和样式属性是减少的,但我只保留它用于测试目的,当我能够解决这个问题时我将删除对齐属性。

当我遇到对齐标签时,这当然不会保留我添加的样式属性。所以我想要实现的是使用clean来删除除了仅包含text-align值的样式之外的所有内容(也就是说,它将清除任何其他样式属性,甚至包含text-align和其他内容的那些属性)

我知道通过改变这样的最后一部分它可以起作用:

wl.addAttributes(":all", "align");
html.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
result = Jsoup.clean(html.body().html(), wl);
html = Jsoup.parse(result, "/");
this.editStyle(html, "[align='center']", "style", "text-align: center");
this.editStyle(html, "[align='justify']", "style", "text-align: justify");
result = html.html();

我从clean获取原始html,再次使用jsoup解析它,并在此时添加属性,而不是在清除之前调用editStyle

但我想知道是否有一些方法只需一步即可完成

1 个答案:

答案 0 :(得分:0)

由于没有答案,我猜这是不可能的,所以我只是在清理之后再次解析文档,根据我已经在问题中发布的替代解决方案

wl.addAttributes(":all", "align");
html.outputSettings(new Document.OutputSettings().prettyPrint(false));//makes html() preserve linebreaks and spacing
result = Jsoup.clean(html.body().html(), wl);
html = Jsoup.parse(result, "/");
this.editStyle(html, "[align='center']", "style", "text-align: center");
this.editStyle(html, "[align='justify']", "style", "text-align: justify");
result = html.html();
相关问题