Sonson
Sonson

Reputation: 1139

Use jsoup to encode Html characters

I have to encode characters to Html:

< to &lt;
> to &gt;
' to &#39;
" to &quot;
& to &amp;

I look for a utility function like htmlspecialchars in PHP:

String htmlspecialchars(String inputText)

Is it possible to use JSoup to encode these characters?

(I have found htmlEscape in the Spring framework, but I don't want to use the Spring framework just for this simple function.)

Upvotes: 5

Views: 9339

Answers (4)

Michael Forstner
Michael Forstner

Reputation: 302

If you have already JSoup on the classpath, just use org.jsoup.nodes.Entities#escape(java.lang.String)

Upvotes: 5

hypomnesis
hypomnesis

Reputation: 21

You can fake it with Jsoup, but I'm sure the other solutions are more thorough and probably less wasteful. You could use some variant of this:

public static String escapeHtml(String text) {
    return (new TextNode(text, "")).toString();
}

With this,

System.out.println(HtmlUtils.escapeHtml("I <don't> \"want\" to see &s and >s."));

yields:

I &lt;don't&gt; "want" to see &amp;s and &gt;s.

You'll note the question marks are not escaped.

Upvotes: 2

newbie
newbie

Reputation: 24635

Apache Commons has StringEscapeUtils and it has escapeHtml method.

import org.apache.commons.lang.StringEscapeUtils;

public class MainClass {
    public static void main(String[] args) {
        String strHTMLInput = "<P>MyName<P>";
        String strEscapeHTML = StringEscapeUtils.escapeHtml(strHTMLInput);
        String strUnEscapeHTML = StringEscapeUtils.unescapeHtml(strEscapeHTML);
        System.out.println("Escaped HTML >>> " + strEscapeHTML);
        System.out.println("UnEscaped HTML >>> " + strUnEscapeHTML);
    }
}

http://www.java2s.com/Tutorial/Java/0500__Apache-Common/StringEscape.htm

Upvotes: 10

vacuum
vacuum

Reputation: 2273

JSoup is a library to parse the HTML.

I dont think you can use it to encode special characters into HTML.

The best way to do it, is to write your own method. Simply you can grab this method from Spring and you dont need to setup whole framework. See source code.

Upvotes: 2

Related Questions