StringEscapeUtils.escapeXml is converting utf8 characters which it should not

public String escapeXml(String s) {
    return s.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
}

The javadoc for the 3.1 version of the library says:

Note that Unicode characters greater than 0x7f are as of 3.0, no longer escaped. If you still wish this functionality, you can achieve it via the following: StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );

So you probably use an older version of the library. Update your dependencies (or reimplement the escape yourself: it's not rocket science)


The javadoc of StringEscapeUtils.escapeXml says that we have to use

StringEscapeUtils.ESCAPE_XML.with( new UnicodeEscaper(Range.between(0x7f, Integer.MAX_VALUE)) );

But instead of UnicodeEscaper, NumericEntityEscaper has to be used. UnicodeEscaper will change everything to \u1234 symbols, but NumericEntityEscaper escapes as &amp;#123;, that was expected.

package mypackage;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.NumericEntityEscaper;

public class XmlEscaper {
    public static void main(final String[] args) {
        final String xmlToEscape = "<hello>Hi</hello>" + "_ _" + "__ __"  + "___ ___" + "after &nbsp;"; // the line cont

        // no Unicode escape
        final String escapedXml = StringEscapeUtils.escapeXml(xmlToEscape);

        // escape Unicode as numeric codes. For instance, escape non-breaking space as &#160;
        final CharSequenceTranslator translator = StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );
        final String escapedXmlWithUnicode = translator.translate(xmlToEscape);

        System.out.println("xmlToEscape: " + xmlToEscape);
        System.out.println("escapedXml: " + escapedXml); // does not escape Unicode characters like non-breaking space
        System.out.println("escapedXml with unicode: " + escapedXmlWithUnicode); // escapes Unicode characters
    }
}