how to convert HTML text to plain text?

Viewed 90254

friend's I have to parse the description from url,where parsed content have few html tags,so how can I convert it to plain text.

10 Answers

Yes, Jsoup will be the better option. Just do like below to convert the whole HTML text to plain text.

String plainText= Jsoup.parse(yout_html_text).text();

Use Jsoup.

Add the dependency

<dependency>
  <!-- jsoup HTML parser library @ https://jsoup.org/ -->
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.13.1</version>
</dependency>

Now in your java code:

public static String html2text(String html) {
        return Jsoup.parse(html).wholeText();
    }

Just call the method html2text with passing the html text and it will return plain text.

I needed a plain text representation of some HTML which included FreeMarker tags. The problem was handed to me with a JSoup solution, but JSoup was escaping the FreeMarker tags, thus breaking the functionality. I also tried htmlCleaner (sourceforge), but that left the HTML header and style content (tags removed). http://stackoverflow.com/questions/1518675/open-source-java-library-for-html-to-text-conversion/1519726#1519726

My code:

return new net.htmlparser.jericho.Source(html).getRenderer().setMaxLineLength(Integer.MAX_VALUE).setNewLine(null).toString();

The maxLineLength ensures lines are not artificially wrapped at 80 characters. The setNewLine(null) uses the same new line character(s) as the source.

I use HTMLUtil.textFromHTML(value) from

<dependency>
    <groupId>org.clapper</groupId>
    <artifactId>javautil</artifactId>
    <version>3.2.0</version>
</dependency>

Using Jsoup, I got all the text in the same line.

So I used the following block of code to parse HTML and keep new lines:

private String parseHTMLContent(String toString) {
    String result = toString.replaceAll("\\<.*?\\>", "\n");
    String previousResult = "";
    while(!previousResult.equals(result)){
        previousResult = result;
        result = result.replaceAll("\n\n","\n");
    }
    return result;
}

Not the best solution but solved my problem :)

Related