【问题标题】:How to filter out illegal XML character in Java如何在 Java 中过滤掉非法的 XML 字符
【发布时间】:2011-06-12 03:50:38
【问题描述】:

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

有人将非法字符放入我们的数据库中。

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

我收到一个错误,例如:

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', ' ')
  • 错误信息中的code 18是指非法字符吗? 0x18 = 24 = control-char "CAN"18 = 0x12 = control-char "DC2" 在人们设法将控制字符输入数据库之前,我已经看到“非法字符”错误。
  • 我不得不假设它是 DC2,尽管我不确定它是如何进入我们的数据库的。
  • 使用 apache Xalan stackoverflow.com/a/9635310/489364987654322@的简洁解决方案

标签: java xml web-services string soap


【解决方案1】:
/**
 * 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();
}

【讨论】:

    【解决方案2】:

    看看这个:

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

    像魅力一样工作。

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2010-12-15
      相关资源
      最近更新 更多