【发布时间】:2017-05-31 06:43:43
【问题描述】:
大家好。我正在尝试将 HTML 代码保存在数据库中,并且我正在使用 SHEF(Swing HTML Editor Framework),但我遇到了一个大问题。通常,生成的 HTML 是这样的:
<div>
This is the first paragraph
</div>
<div>
This is the second paragraph.
</div>
<div>
This is the last paragraph.
</div>
我想“清理” html 代码并使结果看起来像这样:
<div>
This is the first paragraph
<br>
This is the second paragraph.
<br>
This is the last paragraph.
</div>
我尝试使用HTMLCleaner 和JSoup,但我没有成功。我只能让 JSoup 工作,这样
<div>
This is the first paragraph
</div>
<div>
</div>
<div>
This is the last paragraph.
</div>
变成
<div>
This is the first paragraph
</div>
<br>
<div>
This is the last paragraph.
</div>
这是我使用的 JSoup 代码:
Document source = Jsoup.parse(sourceString);
// For each element
for(Element el: source.select("*")) {
if(el.children().isEmpty() && !el.hasText() && el.isBlock()) {
el.replaceWith(new Element(Tag.valueOf("br"), ""));//replace empty tags with newline
}
}
return source.body().html();
有没有办法让生成的 HTML 代码更短?谢谢!
【问题讨论】:
-
清理/编辑 HTML 与 Swing 无关。不要仅仅因为应用程序而添加 Swing 标签。使用一些 Swing API。
标签: java html jsoup htmlcleaner