从 SOAP 消息与文档生成器创建 XML 文档[两者的来源都是输入流]

Creating XML document from SOAP Message vs Document Builder[Source for both is Input Stream]

我主要是尝试通过检查响应对象来检查服务中的故障 我收到来自 SOAP 服务的响应,我希望它是这样的: 以下是输入流

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">
    <S:Body>
        <S:Fault xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope/">
            <S:Code>
                <S:Value>S:Receiver</S:Value>
            </S:Code>
            <S:Reason>
                <S:Text xml:lang="en">org.xml.sax.SAXParseException; cvc-complex-type.2.4.b: The content of element 'ns2:MYREQ' is not complete. One of '{"urn:SOMETHINGELSE}' is expected.</S:Text>
            </S:Reason>
        </S:Fault>
    </S:Body>
</S:Envelope>

。 当我使用以下代码将其转换为 SOAP 消息文档时:

SOAPMessage message = MessageFactory.newInstance("SOAP 1.2 Protocol").createMessage(null, response);
        Document responseDocument = message.getSOAPBody().extractContentAsDocument();

肥皂信封被剪掉了,我只有

<S:Fault xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope/">
                <S:Code>
                    <S:Value>S:Receiver</S:Value>
                </S:Code>
                <S:Reason>
                    <S:Text xml:lang="en">org.xml.sax.SAXParseException; cvc-complex-type.2.4.b: The content of element 'ns2:MYREQ' is not complete. One of '{"urn:SOMETHINGELSE}' is expected.</S:Text>
                </S:Reason>
            </S:Fault>

但是当我使用文档生成器这样做时,我得到了正确的输出

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();

                Document responseDocument = builder.parse(response);

请告诉我为什么当我将 InputStream 转换为 SOAP 消息然后转换为文档时,缺少信封和正文。

message.getSOAPBody().extractContentAsDocument();

此处您要求 return SOAP 响应的 <S:Body> 标记内的所有内容。如果你想得到信封, SOAPPart sp = message.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope();

https://docs.oracle.com/javase/7/docs/api/javax/xml/soap/SOAPMessage.html

所述

而在第二个选项中,您使用的是 DOM API 而不是 SOAP API。这就像将任何 xml 字符串转换为 Document。因此,整个 SOAP 消息被转换为简单的 DOM 文档,您可以从 SOAP 响应访问每个节点。