I have to encode characters to Html:
< to <
> to >
' to '
" to "
& to &
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.)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With