"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-07
Browse:799

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:

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

Implementing Line Break Preservation:

For a more refined solution that preserves line breaks:

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)); }

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).

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3