【问题标题】:How to shorten HTML Code using JSoup or HTMLCleaner如何使用 JSoup 或 HTMLCleaner 缩短 HTML 代码
【发布时间】: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>

我尝试使用HTMLCleanerJSoup,但我没有成功。我只能让 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


【解决方案1】:

我建议,与其摆弄 HTML 并尝试将其最小化,不如将其 gzip 压缩并将其保存到您的数据库中(并在退出时膨胀)。

CPU 开销最小,节省的成本会高得多。而且您的代码将更简单,更通用。用于 HTML 的 gzip 通常会提供 75%-80% 的压缩率,而删除一些标签会给你带来什么,10%?

这是一个如何compress / decompress的示例。

【讨论】:

  • 我可以这样做,但这会影响其他现有的应用程序:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多