score:207

Accepted answer

i have used the apache commons stringescapeutils.unescapehtml4() for this:

unescapes a string containing entity escapes to a string containing the actual unicode characters corresponding to the escapes. supports html 4.0 entities.

score:-7

incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,

static map<string,string> html_specialchars_table = new hashtable<string,string>();
static {
        html_specialchars_table.put("&lt;","<");
        html_specialchars_table.put("&gt;",">");
        html_specialchars_table.put("&amp;","&");
}
static string htmlspecialchars_decode_ent_noquotes(string s){
        enumeration en = html_specialchars_table.keys();
        while(en.hasmoreelements()){
                string key = en.nextelement();
                string val = html_specialchars_table.get(key);
                s = s.replaceall(key, val);
        }
        return s;
}

score:0

consider using the htmlmanipulator java class. you may need to add some items (not all entities are in the list).

the apache commons stringescapeutils as suggested by kevin hakanson did not work 100% for me; several entities like &#145 (left single quote) were translated into '222' somehow. i also tried org.jsoup, and had the same problem.

score:0

in my case i use the replace method by testing every entity in every variable, my code looks like this:

text = text.replace("&ccedil;", "ç");
text = text.replace("&ccedil;", "ç");
text = text.replace("&aacute;", "á");
text = text.replace("&acirc;", "â");
text = text.replace("&atilde;", "ã");
text = text.replace("&eacute;", "é");
text = text.replace("&ecirc;", "ê");
text = text.replace("&iacute;", "í");
text = text.replace("&ocirc;", "ô");
text = text.replace("&otilde;", "õ");
text = text.replace("&oacute;", "ó");
text = text.replace("&uacute;", "ú");
text = text.replace("&aacute;", "á");
text = text.replace("&acirc;", "â");
text = text.replace("&atilde;", "ã");
text = text.replace("&eacute;", "é");
text = text.replace("&ecirc;", "ê");
text = text.replace("&iacute;", "í");
text = text.replace("&ocirc;", "ô");
text = text.replace("&otilde;", "õ");
text = text.replace("&oacute;", "ó");
text = text.replace("&uacute;", "ú");

in my case this worked very well.

score:0

stringescapeutils (apache commons lang)
escapes and unescapes strings for java, javascript, html, and xml.

import org.apache.commons.lang.stringescapeutils;
....
stringescapeutils.unescapehtml(comment);

reference: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/stringescapeutils.html

score:3

the most reliable way is with

string cleanedstring = stringescapeutils.unescapehtml4(originalstring);

from org.apache.commons.lang3.stringescapeutils.

and to escape the whitespaces

cleanedstring = cleanedstring.trim();

this will ensure that whitespaces due to copy and paste in web forms to not get persisted in db.

score:4

a very simple but inefficient solution without any external library is:

public static string unescapehtml3( string str ) {
    try {
        htmldocument doc = new htmldocument();
        new htmleditorkit().read( new stringreader( "<html><body>" + str ), doc, 0 );
        return doc.gettext( 1, doc.getlength() );
    } catch( exception ex ) {
        return str;
    }
}

this should be use only if you have only small count of string to decode.

score:11

this did the job for me,

import org.apache.commons.lang.stringescapeutils;
...
string decodedxml= stringescapeutils.unescapehtml(encodedxml);

or

import org.apache.commons.lang3.stringescapeutils;
...
string decodedxml= stringescapeutils.unescapehtml4(encodedxml);

i guess its always better to use the lang3 for obvious reasons. hope this helps :)

score:11

spring framework htmlutils

if you're using spring framework already, use the following method:

import static org.springframework.web.util.htmlutils.htmlunescape;

...

string result = htmlunescape(source);

score:16

the following library can also be used for html escaping in java: unbescape.

html can be unescaped this way:

final string unescapedtext = htmlescape.unescapehtml(escapedtext); 

score:46

i tried apache commons stringescapeutils.unescapehtml3() in my project, but wasn't satisfied with its performance. turns out, it does a lot of unnecessary operations. for one, it allocates a stringwriter for every call, even if there's nothing to unescape in the string. i've rewritten that code differently, now it works much faster. whoever finds this in google is welcome to use it.

following code unescapes all html 3 symbols and numeric escapes (equivalent to apache unescapehtml3). you can just add more entries to the map if you need html 4.

package com.example;

import java.io.stringwriter;
import java.util.hashmap;

public class stringutils {

    public static final string unescapehtml3(final string input) {
        stringwriter writer = null;
        int len = input.length();
        int i = 1;
        int st = 0;
        while (true) {
            // look for '&'
            while (i < len && input.charat(i-1) != '&')
                i++;
            if (i >= len)
                break;

            // found '&', look for ';'
            int j = i;
            while (j < len && j < i + max_escape + 1 && input.charat(j) != ';')
                j++;
            if (j == len || j < i + min_escape || j == i + max_escape + 1) {
                i++;
                continue;
            }

            // found escape 
            if (input.charat(i) == '#') {
                // numeric escape
                int k = i + 1;
                int radix = 10;

                final char firstchar = input.charat(k);
                if (firstchar == 'x' || firstchar == 'x') {
                    k++;
                    radix = 16;
                }

                try {
                    int entityvalue = integer.parseint(input.substring(k, j), radix);

                    if (writer == null) 
                        writer = new stringwriter(input.length());
                    writer.append(input.substring(st, i - 1));

                    if (entityvalue > 0xffff) {
                        final char[] chrs = character.tochars(entityvalue);
                        writer.write(chrs[0]);
                        writer.write(chrs[1]);
                    } else {
                        writer.write(entityvalue);
                    }

                } catch (numberformatexception ex) { 
                    i++;
                    continue;
                }
            }
            else {
                // named escape
                charsequence value = lookupmap.get(input.substring(i, j));
                if (value == null) {
                    i++;
                    continue;
                }

                if (writer == null) 
                    writer = new stringwriter(input.length());
                writer.append(input.substring(st, i - 1));

                writer.append(value);
            }

            // skip escape
            st = j + 1;
            i = st;
        }

        if (writer != null) {
            writer.append(input.substring(st, len));
            return writer.tostring();
        }
        return input;
    }

    private static final string[][] escapes = {
        {"\"",     "quot"}, // " - double-quote
        {"&",      "amp"}, // & - ampersand
        {"<",      "lt"}, // < - less-than
        {">",      "gt"}, // > - greater-than

        // mapping to escape iso-8859-1 characters to their named html 3.x equivalents.
        {"\u00a0", "nbsp"}, // non-breaking space
        {"\u00a1", "iexcl"}, // inverted exclamation mark
        {"\u00a2", "cent"}, // cent sign
        {"\u00a3", "pound"}, // pound sign
        {"\u00a4", "curren"}, // currency sign
        {"\u00a5", "yen"}, // yen sign = yuan sign
        {"\u00a6", "brvbar"}, // broken bar = broken vertical bar
        {"\u00a7", "sect"}, // section sign
        {"\u00a8", "uml"}, // diaeresis = spacing diaeresis
        {"\u00a9", "copy"}, // © - copyright sign
        {"\u00aa", "ordf"}, // feminine ordinal indicator
        {"\u00ab", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
        {"\u00ac", "not"}, // not sign
        {"\u00ad", "shy"}, // soft hyphen = discretionary hyphen
        {"\u00ae", "reg"}, // ® - registered trademark sign
        {"\u00af", "macr"}, // macron = spacing macron = overline = apl overbar
        {"\u00b0", "deg"}, // degree sign
        {"\u00b1", "plusmn"}, // plus-minus sign = plus-or-minus sign
        {"\u00b2", "sup2"}, // superscript two = superscript digit two = squared
        {"\u00b3", "sup3"}, // superscript three = superscript digit three = cubed
        {"\u00b4", "acute"}, // acute accent = spacing acute
        {"\u00b5", "micro"}, // micro sign
        {"\u00b6", "para"}, // pilcrow sign = paragraph sign
        {"\u00b7", "middot"}, // middle dot = georgian comma = greek middle dot
        {"\u00b8", "cedil"}, // cedilla = spacing cedilla
        {"\u00b9", "sup1"}, // superscript one = superscript digit one
        {"\u00ba", "ordm"}, // masculine ordinal indicator
        {"\u00bb", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
        {"\u00bc", "frac14"}, // vulgar fraction one quarter = fraction one quarter
        {"\u00bd", "frac12"}, // vulgar fraction one half = fraction one half
        {"\u00be", "frac34"}, // vulgar fraction three quarters = fraction three quarters
        {"\u00bf", "iquest"}, // inverted question mark = turned question mark
        {"\u00c0", "agrave"}, // а - uppercase a, grave accent
        {"\u00c1", "aacute"}, // б - uppercase a, acute accent
        {"\u00c2", "acirc"}, // в - uppercase a, circumflex accent
        {"\u00c3", "atilde"}, // г - uppercase a, tilde
        {"\u00c4", "auml"}, // д - uppercase a, umlaut
        {"\u00c5", "aring"}, // е - uppercase a, ring
        {"\u00c6", "aelig"}, // ж - uppercase ae
        {"\u00c7", "ccedil"}, // з - uppercase c, cedilla
        {"\u00c8", "egrave"}, // и - uppercase e, grave accent
        {"\u00c9", "eacute"}, // й - uppercase e, acute accent
        {"\u00ca", "ecirc"}, // к - uppercase e, circumflex accent
        {"\u00cb", "euml"}, // л - uppercase e, umlaut
        {"\u00cc", "igrave"}, // м - uppercase i, grave accent
        {"\u00cd", "iacute"}, // н - uppercase i, acute accent
        {"\u00ce", "icirc"}, // о - uppercase i, circumflex accent
        {"\u00cf", "iuml"}, // п - uppercase i, umlaut
        {"\u00d0", "eth"}, // р - uppercase eth, icelandic
        {"\u00d1", "ntilde"}, // с - uppercase n, tilde
        {"\u00d2", "ograve"}, // т - uppercase o, grave accent
        {"\u00d3", "oacute"}, // у - uppercase o, acute accent
        {"\u00d4", "ocirc"}, // ф - uppercase o, circumflex accent
        {"\u00d5", "otilde"}, // х - uppercase o, tilde
        {"\u00d6", "ouml"}, // ц - uppercase o, umlaut
        {"\u00d7", "times"}, // multiplication sign
        {"\u00d8", "oslash"}, // ш - uppercase o, slash
        {"\u00d9", "ugrave"}, // щ - uppercase u, grave accent
        {"\u00da", "uacute"}, // ъ - uppercase u, acute accent
        {"\u00db", "ucirc"}, // ы - uppercase u, circumflex accent
        {"\u00dc", "uuml"}, // ь - uppercase u, umlaut
        {"\u00dd", "yacute"}, // э - uppercase y, acute accent
        {"\u00de", "thorn"}, // ю - uppercase thorn, icelandic
        {"\u00df", "szlig"}, // я - lowercase sharps, german
        {"\u00e0", "agrave"}, // а - lowercase a, grave accent
        {"\u00e1", "aacute"}, // б - lowercase a, acute accent
        {"\u00e2", "acirc"}, // в - lowercase a, circumflex accent
        {"\u00e3", "atilde"}, // г - lowercase a, tilde
        {"\u00e4", "auml"}, // д - lowercase a, umlaut
        {"\u00e5", "aring"}, // е - lowercase a, ring
        {"\u00e6", "aelig"}, // ж - lowercase ae
        {"\u00e7", "ccedil"}, // з - lowercase c, cedilla
        {"\u00e8", "egrave"}, // и - lowercase e, grave accent
        {"\u00e9", "eacute"}, // й - lowercase e, acute accent
        {"\u00ea", "ecirc"}, // к - lowercase e, circumflex accent
        {"\u00eb", "euml"}, // л - lowercase e, umlaut
        {"\u00ec", "igrave"}, // м - lowercase i, grave accent
        {"\u00ed", "iacute"}, // н - lowercase i, acute accent
        {"\u00ee", "icirc"}, // о - lowercase i, circumflex accent
        {"\u00ef", "iuml"}, // п - lowercase i, umlaut
        {"\u00f0", "eth"}, // р - lowercase eth, icelandic
        {"\u00f1", "ntilde"}, // с - lowercase n, tilde
        {"\u00f2", "ograve"}, // т - lowercase o, grave accent
        {"\u00f3", "oacute"}, // у - lowercase o, acute accent
        {"\u00f4", "ocirc"}, // ф - lowercase o, circumflex accent
        {"\u00f5", "otilde"}, // х - lowercase o, tilde
        {"\u00f6", "ouml"}, // ц - lowercase o, umlaut
        {"\u00f7", "divide"}, // division sign
        {"\u00f8", "oslash"}, // ш - lowercase o, slash
        {"\u00f9", "ugrave"}, // щ - lowercase u, grave accent
        {"\u00fa", "uacute"}, // ъ - lowercase u, acute accent
        {"\u00fb", "ucirc"}, // ы - lowercase u, circumflex accent
        {"\u00fc", "uuml"}, // ь - lowercase u, umlaut
        {"\u00fd", "yacute"}, // э - lowercase y, acute accent
        {"\u00fe", "thorn"}, // ю - lowercase thorn, icelandic
        {"\u00ff", "yuml"}, // я - lowercase y, umlaut
    };

    private static final int min_escape = 2;
    private static final int max_escape = 6;

    private static final hashmap<string, charsequence> lookupmap;
    static {
        lookupmap = new hashmap<string, charsequence>();
        for (final charsequence[] seq : escapes) 
            lookupmap.put(seq[1].tostring(), seq[0]);
    }

}

score:63

the libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the jsoup project has a lot more to offer than just managing "ampersand pound ffff semicolon" things.

// textvalue: <p>this is a&nbsp;sample. \"granny\" smith &#8211;.<\/p>\r\n
// becomes this: this is a sample. "granny" smith –.
// with one line of code:
// jsoup.parse(textvalue).gettext(); // for older versions of jsoup
jsoup.parse(textvalue).text();

// another possibility may be the static unescapeentities method:
boolean strictmode = true;
string unescapedstring = org.jsoup.parser.parser.unescapeentities(textvalue, strictmode);

and you also get the convenient api for extracting and manipulating data, using the best of dom, css, and jquery-like methods. it's open source and mit licence.


Related Query

More Query from same tag