如何修复无效的 XML 以便它可以被 Spring WebServiceTemplate 使用

How to fix an invalid XML so it can be consumed by Spring WebServiceTemplate

我正在使用 Spring 的 WebServiceTemplate 来使用 Soap 服务。有时,此 Soap 服务会返回无效的 XML。我想拦截它的解析器并在解析之前修复无效的 XML 。我怎么能那样做?现在我正在打电话:

wsTemplate.sendSourceAndReceiveToResult(new StreamSource(new StringInputStream(msg)),new StreamResult(stringWriter))

我想我必须调用 sendSourceAndReceive 并定义我自己的 SourceExtractor 但是当我实际上想做一些简单的事情时,这似乎我在这个过程中干预太多了。

这是我要解决的问题:

An invalid XML character (Unicode: 0x1f) was found in the element content of the document.

SystemErr     R    at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java :210)

该字符在 XML 1.1 中被接受,但文档被描述为 XML 1.0:

<?xml version="1.0" encoding="utf-8"?>

所以我想要的是将那个字符替换为制表符或 space。

我能够通过如下装饰 webServiceTemplate 的 WebServiceMessageFactory 来修复消息:

final WebServiceMessageFactory mfOriginal = myWebServiceTemplate.getMessageFactory();
WebServiceMessageFactory mfDecorator = new WebServiceMessageFactory() {
    @Override
    public WebServiceMessage createWebServiceMessage(final InputStream inputStream) throws InvalidXmlException, IOException {
        InputStream decoratedIs = new InputStream() {

            @Override
            public int read() throws IOException {
                int nextByte = inputStream.read();
                // Replacing the invalid character with a tab. Touching nothing else.
                if (nextByte == 0x1f) {
                    nextByte = 0x09;
                }
                return nextByte;
            }
        };
        return mfOriginal.createWebServiceMessage(decoratedIs);
    }

    @Override
    public WebServiceMessage createWebServiceMessage() {
        return mfOriginal.createWebServiceMessage();
    }
};
myServiceTemplate.setMessageFactory(mfDecorator);