使用CXF时,如何处理WS输出中的无效字符?

2022-09-02 21:07:51

我正在使用Spring,CXF和Hibernate来构建一个WebService,该服务对具有只读访问权限的外部数据库执行搜索查询。

问题在于,数据库中的某些条目在文本字段中具有奇怪的字符(0x2),并且似乎CXF或它用于处理/序列化从Hibernate会话返回的对象的库(Aegis?)无法处理它:

org.apache.cxf.aegis.DatabindingException: Error writing document.. Nested exception is com.ctc.wstx.exc.WstxIOException: Invalid white space character (0x2) in text to output (in xml 1.1, could output as a character entity)

我该如何解决这个问题?理想情况下,我可以删除这些字符,因为它们对我的输出无关紧要......谢谢!


答案 1
/**
* From xml spec valid chars:<br>
* #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]<br>
* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.<br>
* @param text The String to clean
* @param replacement The string to be substituted for each match
* @return The resulting String
*/
public static String CleanInvalidXmlChars(String text, String replacement) {
    String re = "[^\u0009\r\n\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF]";
    return text.replaceAll(re, replacement);
}

来源:http://www.theplancollection.com/house-plan-related-articles/hexadecimal-value-invalid-characterheplancollection.com/house-plan-related-articles/hexadecimal-value-invalid-character


答案 2

我不确定这是否回答了你的问题,但这是我的发现。

下面是引发异常的类:http://svn.codehaus.org/woodstox/wstx/trunk/src/java/com/ctc/wstx/api/InvalidCharHandler.java

似乎这里有一个关于这个问题的讨论:http://comments.gmane.org/gmane.comp.apache.cxf.user/4373

也许这可以让你:还可以将终结点/总线上的“disable.outputstream.optimization”属性设置为 true,以使其禁用对输出流的直接写入并始终通过 XMLStreamWriter。应该完成同样的事情,而不会产生创建SAAJModel的开销。

希望这有帮助一点。


推荐