解析XML不会在父节点和子节点中保留重复的命名空间

Die*_*nia 8 java xml spring-ws xml-namespaces xml-parsing

在开始之前:我知道子节点从父节点继承命名空间,这就是我的问题发生的原因.不幸的是,我发送XML的Web服务不接受没有命名空间的子节点,并且因为它是一个政府实体,所以它们的部分变化是不太可能的.

话虽这么说,我使用Spring-WS在我的应用程序和Web服务之间进行通信,因此框架使用变换器以一种方式使用转换器将我的有效负载源解析为框架的有效负载结果:

transformer.transform(Source, Result);
Run Code Online (Sandbox Code Playgroud)

在进行转换之前,我的XML有这两个节点,如下所示:

<enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
   <NFe xmlns="http://www.portalfiscal.inf.br/nfe">
Run Code Online (Sandbox Code Playgroud)

转换后,第二个命名空间被删除(正如我之前所说,我知道原因):

<enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
   <NFe>
Run Code Online (Sandbox Code Playgroud)

我也知道我可以使用marshallers来实现相同的结果并自己编写解析代码.使用这种方法也是可以接受的,但我不知道使用除上面列出的方法之外的其他方法来实现相同的事情(转换javax.xml.transform.Sourcejavax.xml.transform.Result).

那我有两个问题:

1 - 我可以避免使用默认方法(不使用marshallers)的行为吗?

2 - 是否还有其他工具可以进行相同的转换?

Dan*_*ves 1

我也经历过同样的麻烦。不幸的是(或没有)带有 SOAPMessageFactory(例如 SaajSoapMessageFactory)实现的 WebServiceTemplate 将尽一切可能通过将您从源到结果绑定到 Transformer 来确保您发送格式良好的 XML 作为请求,包括绝不让您重复 'xmlns ’在孩子身上,当你已经在父母身上做过的时候。您可以尝试几个优雅的选项 - 但这并不意味着它们是最简单的。您可以使用 javax.xml.ws.Service 和 Dispatch 接口在 XML 级别工作,如果您不需要 SSL 身份验证,这非常容易。查看这些链接(第一个是用 Pt-BR 编写的):

http://www.guj.com.br/t/nfe-v2-00-veja-como-consumir-o-ws/297304

https://alesaudate.wordpress.com/2010/08/09/how-to-dynamically-select-a-certificate-alias-when-invoking-web-services/

您也可以尝试其他消息工厂,例如 DomPoxMessageFactory。此链接可能有用:

http://forum.spring.io/forum/spring-projects/web-services/128221-webservicetemplate-get-it-to-stop-adding-soap-envelope

但是,如果无法更改项目结构(这就是我的情况),我为您提供了一个解决方法。是的,这是一种解决方法,但是一旦目标 Web 服务预期格式错误的 XML,我就原谅自己了 :D

我刚刚创建了 HttpComponentsMessageSender 和 HttpComponentsConnection 类的抽象,第二个类是通过第一个类的方法 createConnection(URI uri) 实例化的。所以我可以像这样创建我的 WebServiceTemplate:

WebServiceTemplate wst = new WebServiceTemplate(new SaajSoapMessageFactory());
wst.setMessageSender(new CustomHttpComponentsMessageSender());
Run Code Online (Sandbox Code Playgroud)

遗憾的是,您需要将 createConnecion 方法回复到新的抽象,只是为了实例化自定义连接。正如我所说,这是一个解决方法!

@Override
public WebServiceConnection createConnection(URI uri) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    if (isAcceptGzipEncoding()) {
        httpPost.addHeader(HttpTransportConstants.HEADER_ACCEPT_ENCODING,
                HttpTransportConstants.CONTENT_ENCODING_GZIP);
    }
    HttpContext httpContext = createContext(uri);
    return new CustomHttpComponentsConnection(getHttpClient(), httpPost, httpContext);
}
Run Code Online (Sandbox Code Playgroud)

该消息在我从中抽象的 HttpComponentsConnection 类的 onSendAfterWrite(WebServiceMessage message) 方法中有效发送。令人惊讶的是,该方法内部没有使用“message”参数。它仅用于继承规则。好消息是:这是一种受保护的方法。缺点是,一旦字段没有公共可见性,并且框架在响应处理中需要它们,我需要复制几乎整个类才能仅更改此方法。所以,我会把我的整个课程贴下来:

public class CustomHttpComponentsConnection extends HttpComponentsConnection {

    private final HttpClient httpClient;

    private final HttpPost httpPost;

    private final HttpContext httpContext;

    private HttpResponse httpResponse;

    private ByteArrayOutputStream requestBuffer;

    protected CustomHttpComponentsConnection(HttpClient httpClient, HttpPost httpPost, HttpContext httpContext) {
        super(httpClient, httpPost, httpContext);

        Assert.notNull(httpClient, "httpClient must not be null");
        Assert.notNull(httpPost, "httpPost must not be null");
        this.httpClient = httpClient;
        this.httpPost = httpPost;
        this.httpContext = httpContext;
    }

    public HttpResponse getHttpResponse() {
    return httpResponse;
    }

    public HttpPost getHttpPost() {
        return httpPost;
    }

    @Override
    protected OutputStream getRequestOutputStream() throws IOException {
        return requestBuffer;
    }

    @Override
    protected void onSendBeforeWrite(WebServiceMessage message) throws IOException {
        requestBuffer = new ByteArrayOutputStream();
    }

    @Override
    protected void onSendAfterWrite(WebServiceMessage message) throws IOException {

        OutputStream out = getRequestOutputStream();

        String str = out.toString();

        str = str.replaceAll("<NFe>", "<NFe xmlns=\"http://www.portalfiscal.inf.br/nfe\">");
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        bs.write(str.getBytes());

        getHttpPost().setEntity(new ByteArrayEntity(bs.toByteArray()));

        requestBuffer = null;
        if (httpContext != null) {
            httpResponse = httpClient.execute(httpPost, httpContext);
        }
        else {
            httpResponse = httpClient.execute(httpPost);
        }
    }

    @Override
    protected int getResponseCode() throws IOException {
        return httpResponse.getStatusLine().getStatusCode();
    }

    @Override
    protected String getResponseMessage() throws IOException {
        return httpResponse.getStatusLine().getReasonPhrase();
    }

    @Override
    protected long getResponseContentLength() throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            return entity.getContentLength();
        }
        return 0;
    }

    @Override
    protected InputStream getRawResponseInputStream() throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
             return entity.getContent();
        }
        throw new IllegalStateException("Response has no enclosing response entity, cannot create input stream");
    }

    @Override
    public Iterator<String> getResponseHeaderNames() throws IOException {
        Header[] headers = httpResponse.getAllHeaders();
        String[] names = new String[headers.length];
        for (int i = 0; i < headers.length; i++) {
            names[i] = headers[i].getName();
        }
        return Arrays.asList(names).iterator();
    }

    @Override
    public Iterator<String> getResponseHeaders(String name) throws IOException {
        Header[] headers = httpResponse.getHeaders(name);
        String[] values = new String[headers.length];
        for (int i = 0; i < headers.length; i++) {
            values[i] = headers[i].getValue();
        }
        return Arrays.asList(values).iterator();
    }
Run Code Online (Sandbox Code Playgroud)

同样,这是我在无法更改项目结构时发现的最简单的方法。希望这可以帮助。