Home  >  Article  >  Java  >  How Can I Preserve Line Breaks When Converting HTML to Plain Text with Jsoup?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 01:15:29162browse

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

Preserving Line Breaks with Jsoup's Html to Plain Text Conversion

Jsoup offers robust tools for manipulating HTML, but its default conversion from HTML to plain text can merge line breaks, rendering them as continuous text. To preserve these breaks, here's how you can utilize Jsoup:

A Custom Function for Line Break Preservation:

The provided Java code snippet introduces a custom function, noTags, that leverages Jsoup's text() method to strip HTML tags from input HTML. However, it does not maintain line breaks.

Enhancing the Function with Whole Text Extraction:

Jsoup's JsonNode class offers a getWholeText() method, which extracts the text content while respecting line breaks. Using this method, the noTags function can be improved:

<code class="java">public String noTags(String str) {
    return Jsoup.parse(str).wholeText();
}</code>

Implementing Line Break Preservation:

For a more refined solution that preserves line breaks:

<code class="java">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 <br> tags
    document.select("br").append("\n");
    // Prepend line breaks for <p> 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));
}</code>

This custom function ensures that line breaks are preserved, aligning with the desired output. It fulfills two key requirements:

  1. Original line breaks (n) are preserved.

  2. and

    tags are converted into line breaks (n).

The above is the detailed content of How Can I Preserve Line Breaks When Converting HTML to Plain Text with Jsoup?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn