使用 Jsoup 解析 html 如何保留 innerText 中的換行符回車符

寫了個小工具用到了 Jsoup 使用中發現,在輸出 html 的時候,innerText 裏面的丟失了 \r\n 換行符回車符,解決這個問題只需關閉 Jsoup 輸出格式化即可。

上代碼,示例如下:

String html = "<!DOCTYPE HTML><html><head><title></title><style></style></head>"
		+ "<body> \r\n hello world! \r\n hello jeesite! \r\n </body></html> ";

Document document = Jsoup.parse(html);

// 默認解析後會進行 格式化 HTML,格式化後丟失了:回車、 換行、 空格
System.out.println(document.html());
System.out.println("==============");

// 輸出設置格式化爲關閉狀態, 原樣輸出,保留:回車、 換行、 空格
document.outputSettings(new Document.OutputSettings().prettyPrint(false));
System.out.println(document.html());

執行結果:

<!doctype html>
<html>
 <head>
  <title></title>
  <style></style>
 </head>
 <body>
   hello world! hello jeesite! 
 </body>
</html>
==============
<!doctype html><html><head><title></title><style></style></head><body> 
 hello world! 
 hello jeesite! 
 </body></html> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章