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

时间:2012-03-14 21:00:28

标签: java xml spring cxf

我正在使用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)

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

4 个答案:

答案 0 :(得分:15)

/**
* 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 = "[^\\x09\\x0A\\x0D\\x20-\\xD7FF\\xE000-\\xFFFD\\x10000-x10FFFF]";
    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

答案 1 :(得分:8)

我不确定这会回答你的问题,但这是我找到的。

以下是抛出异常的类: 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的开销。

希望这有点帮助。

答案 2 :(得分:1)

为了达到理想的行为并避免抛出异常,您必须使用自己的工具扩展默认的Woodstoks工厂com.ctc.wstx.stax.WstxOutputFactory,这应该只会覆盖该属性com.ctc.wstx.outputInvalidCharHandler,其实例为com.ctc.wstx.api.InvalidCharHandler.ReplacingHandler。此处理程序将替换字符作为构造函数参数用于无效字符。使用您的实例,创建一个名为META-INF/services/javax.xml.stream.XMLOutputFactory的文件,并在其中放置实现的完整名称(确保它将被放置在生成的jar中的META-INF / services目录中)。

您可以找到更多详情here

HTH!

答案 3 :(得分:0)

评分最高的答案对我不起作用,因为给定的Unicode编码被拒绝了。然而,稍微改变,它显示了所需的行为:

public static String CleanInvalidXmlChars(String text, String replacement) {
    String re = "[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u0001\\u0000-\\u0010\\uFFFF]";
    return text.replaceAll(re, replacement);
}