How to filter out an illegal XML character in Java

I am creating a web service.

Some place illegal characters in our database.

Now, when I try to extract these lines and send them through a web service, the client suffocates.

I get an error, for example:

com.sun.xml.ws.encoding.soap.DeserializationException: Failed to read a response: javax.xml.bind.UnmarshalException
 - with linked exception:
[com.ctc.wstx.exc.WstxUnexpectedCharException: Illegal character ((CTRL-CHAR, code 18))

How to remove this character in Java?

+3
source share
2 answers
/**
 * Function to strip control characters from a string.
 * Any character below a space will be stripped from the string.
 * @param iString the input string to be stripped.
 * @return a string containing the characters from iString minus any control characters.
 */
public String stripControlChars(String iString) {
    StringBuffer result = new StringBuffer(iString);
    int idx = result.length();
    while (idx-- > 0) {
        if (result.charAt(idx) < 0x20 && result.charAt(idx) != 0x9 && 
                result.charAt(idx) != 0xA && result.charAt(idx) != 0xD) {
            if (log.isDebugEnabled()) {
                log.debug("deleted character at: "+idx);
            }
            result.deleteCharAt(idx);
        }
    }
    return result.toString();
}
+3
source

Check this:

stringName.replaceAll("[^\\p{Print}]", "");

It works like a charm.

+3
source

Source: https://habr.com/ru/post/1786551/


All Articles