このコードを使用して、本質的にすべてから厄介な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);
}
私はそれが整列し、スタイル属性の両方を持っているredudant知っているが、私は修正することができますときに私は、テスト目的のみのためにそれを維持していますこれはalign属性も削除します。
これはもちろん、私が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();
私はjsoupで再びそれを解析し、クリーンから生のHTMLを取得し、
をクリーニングする前に、この時点でeditStyle
を呼び出すのではなく、バック属性を追加しかし、私は1つのステップでそれを行うための何らかの方法があるかどうかを知りたかった。