如何在Java中过滤掉非法的XML字符

4

我正在构建一个网络服务。

有人在我们的数据库中输入了非法字符。

现在当我尝试检索这些字符串并通过网络服务发送它们时,客户端会出问题。

我会得到如下错误:

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))

如何在Java中删除此字符?


我正在寻找快速且简单的方法。我可以使用类似这样的代码:stringName.replace('\u0022', ' ')吗? - jeph perro
可能是Java中将文本数据编码为XML的最佳方法?的重复问题。 - Taylor Leese
在错误信息中,“code 18”是指非法字符吗?0x18 = 24 = control-char "CAN" 或者 18 = 0x12 = control-char "DC2"。我之前见过“非法字符”的错误,当时是因为有人将控制字符输入到了数据库中。 - Stephen P
我必须假设它是DC2,尽管我不确定它是如何进入我们的数据库的。 - jeph perro
使用Apache Xalan的简洁解决方案 https://dev59.com/MnVD5IYBdhLWcg3wGHeu#9635310 - kommradHomer
2个回答

3

看看这个:

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

像魔法一样好用。

3
/**
 * 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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接