”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Jsoup 将 HTML 转换为纯文本时如何保留换行符?

使用 Jsoup 将 HTML 转换为纯文本时如何保留换行符?

发布于2024-11-07
浏览:104

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