2017-01-16 123 views
0

美好的一天,每個人。我試圖在數據庫中保存HTML代碼,我使用的是SHEF(Swing HTML Editor Framework),但是我遇到了一個很大的問題。通常情況下,生成的HTML是這樣的:如何使用JSoup或HTMLCleaner縮短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代碼短?謝謝!

+2

清理/編輯HTML與Swing無關。不要僅因爲應用程序添加Swing標記。使用一些Swing API。 –

回答

2

我會建議,而不是擺弄HTML,並試圖儘量減少它,你只需gzip壓縮它,並將其保存到您的數據庫(而在出路上膨脹)。

CPU開銷很小,節省的成本會更高。而你的代碼將更簡單,更通用。 gzip for HTML通常會提供75%-80%的壓縮比,而刪除一些標籤會給你什麼,10%?

下面是如何compress/decompress的示例。

+0

我可以這樣做,但這會影響其他現有的應用程序:/ – triForce420