今天是个好日子。我正在尝试将 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 代码更短?谢谢!