」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Jsoup 將 HTML 轉換為純文字時如何保留換行符號?

使用 Jsoup 將 HTML 轉換為純文字時如何保留換行符號?

發佈於2024-11-07
瀏覽:912

How Can I Preserve Line Breaks When Converting HTML to Plain Text with Jsoup?

使用Jsoup 的Html 到純文字轉換保留換行符

Jsoup 提供了強大的HTML 操作工具,但其預設從HTML 到純文字的轉換文字可以合併換行符,將它們呈現為連續文字。要保留這些換行符,請按以下方式使用Jsoup:

用於保留換行符的自訂函數:

提供的Java 程式碼片段引入了一個自訂函數noTags,它利用Jsoup 的text()從輸入HTML 中移除HTML 標籤的方法。但是,它不維護換行符。

增強全文本提取功能:

Jsoup 的 JsonNode 類別提供了 getWholeText() 方法,該方法可以在考慮換行符的同時提取文字內容。使用這種方法,可以改進 noTags 功能:

public String noTags(String str) {
    return Jsoup.parse(str).wholeText();
}

實作換行符保留:

有關保留換行符的更精細的解決方案:

public static String br2nl(String html) {
    if (html == null)
        return html;
    Document document = Jsoup.parse(html);
    // Suppress pretty printing to preserve line breaks and spacing
    document.outputSettings(new Document.OutputSettings().prettyPrint(false));
    // Append line breaks for 
tags document.select("br").append("\\n"); // Prepend line breaks for

tags document.select("p").prepend("\\n\\n"); String s = document.html().replaceAll("\\\\n", "\n"); return Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)); }

此自訂函數可確保保留換行符,與所需的輸出對齊。它滿足兩個關鍵要求:

  1. 保留原始換行符號 (\n)。

  2. 標記被轉換為換行符號 (\n)。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3