32

I need to unescape a xml string containing escaped XML tags:

<
>
&
etc...

I did find some libs that can perform this task, but i'd rather use a single method that can perform this task.

Can someone help?

cheers, Bas Hendriks

Bas Hendriks
  • 609
  • 1
  • 7
  • 14

4 Answers4

52
StringEscapeUtils.unescapeXml(xml)

(commons-lang, download)

turbanoff
  • 2,439
  • 6
  • 42
  • 99
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    "but i'd rather use a single method that can perform this task." – Bas Hendriks May 14 '10 at 12:19
  • 1
    Bas, read commons-lang's source code and see if it's worth to reinvent the wheel in your case instead of justing using it. – Felipe Cypriano May 14 '10 at 12:39
  • 1
    @Bas - there's nothing in the standard Java library to do this, so either you use a third-party library that can do this for you, or you have to write it yourself (not recommended). – Jesper May 14 '10 at 14:12
  • 7
    commons-lang seems deprecated, and commons-text should be used. http://commons.apache.org/proper/commons-text https://mvnrepository.com/artifact/org.apache.commons/commons-text/1.6 – Kuro Mar 18 '19 at 18:10
6

Here's a simple method to unescape XML. It handles the predefined XML entities and decimal numerical entities (&#nnnn;). Modifying it to handle hex entities (&#xhhhh;) should be simple.

public static String unescapeXML( final String xml )
{
    Pattern xmlEntityRegex = Pattern.compile( "&(#?)([^;]+);" );
    //Unfortunately, Matcher requires a StringBuffer instead of a StringBuilder
    StringBuffer unescapedOutput = new StringBuffer( xml.length() );

    Matcher m = xmlEntityRegex.matcher( xml );
    Map<String,String> builtinEntities = null;
    String entity;
    String hashmark;
    String ent;
    int code;
    while ( m.find() ) {
        ent = m.group(2);
        hashmark = m.group(1);
        if ( (hashmark != null) && (hashmark.length() > 0) ) {
            code = Integer.parseInt( ent );
            entity = Character.toString( (char) code );
        } else {
            //must be a non-numerical entity
            if ( builtinEntities == null ) {
                builtinEntities = buildBuiltinXMLEntityMap();
            }
            entity = builtinEntities.get( ent );
            if ( entity == null ) {
                //not a known entity - ignore it
                entity = "&" + ent + ';';
            }
        }
        m.appendReplacement( unescapedOutput, entity );
    }
    m.appendTail( unescapedOutput );

    return unescapedOutput.toString();
}

private static Map<String,String> buildBuiltinXMLEntityMap()
{
    Map<String,String> entities = new HashMap<String,String>(10);
    entities.put( "lt", "<" );
    entities.put( "gt", ">" );
    entities.put( "amp", "&" );
    entities.put( "apos", "'" );
    entities.put( "quot", "\"" );
    return entities;
}
texclayton
  • 189
  • 1
  • 4
5

Here is one that I wrote in ten minutes. It does not use regular expressions, only simple iterations. I do not think that this can be enhanced to be much faster.

public static String unescape(final String text) {
    StringBuilder result = new StringBuilder(text.length());
    int i = 0;
    int n = text.length();
    while (i < n) {
        char charAt = text.charAt(i);
        if (charAt != '&') {
            result.append(charAt);
            i++;
        } else {
            if (text.startsWith("&amp;", i)) {
                result.append('&');
                i += 5;
            } else if (text.startsWith("&apos;", i)) {
                result.append('\'');
                i += 6;
            } else if (text.startsWith("&quot;", i)) {
                result.append('"');
                i += 6;
            } else if (text.startsWith("&lt;", i)) {
                result.append('<');
                i += 4;
            } else if (text.startsWith("&gt;", i)) {
                result.append('>');
                i += 4;
            } else i++;
        }
    }
    return result.toString();
}
Community
  • 1
  • 1
Balazs Zsoldos
  • 6,036
  • 2
  • 23
  • 31
0

If you work with JSP, use su:unescapeXml from openutils-elfunctions

msangel
  • 9,895
  • 3
  • 50
  • 69