我想输出一些 SOAPMessage
的内容(在本例中是请求和响应),比如说标准输出,但我在查看内容格式良好:
// Create the Message
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
// In my case I get the content from a known well XML file (which is well formatted, BTW)
SOAPPart sp = msg.getSOAPPart();
StreamSource prepMsg = new StreamSource(new FileInputStream(targetFile));
sp.setContent(prepMsg);
// Add some info, save changes and send to output
SOAPElement soapHeaderElem = msg.getSOAPHeader().addChildElement("header", "","xmlapi_1.0");
SOAPElement securityHeaderElem = soapHeaderElem.addChildElement("security");
SOAPElement userHeaderElem = securityHeaderElem.addChildElement("user");
userHeaderElem.setValue(user);
SOAPElement passHeaderElem = securityHeaderElem.addChildElement("password");
passHeaderElem.addAttribute(new QName("hashed"), String.valueOf(hashedPassword));
passHeaderElem.setValue(password);
msg.saveChanges();
msg.writeTo(System.out);
这里,唯一格式正确的部分是从 XML 加载的部分,其余部分显示在一行中!
<?xml version="1.0" encoding="UTF-8" ?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header>
<header xmlns="xmlapi_1.0"><security><user>****</user><password hashed="false">****</password></security></header></SOAP:Header>
<SOAP:Body>
</SOAP:Body>
</SOAP:Envelope>
另一方面,当我使用 DomSource
和 StreamResult
检查响应正文时,消息内容显示在一行中(所有它):
SOAPMessage rp = soapConnection.call(msg, remoteURL);
// Iterate
Source sc = new DOMSource(rp.getSOAPPart().getEnvelope().getBody().getChildNodes().item(i));
// And for each...
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
StreamResult result = new StreamResult(System.out);
我的问题是:
- 我是否为这些对象设置了任何属性,以便在任何情况下都有格式良好的输出? (类似于 JAXB
Marshaller.JAXB_FORMATTED_OUTPUT
属性)?
- 有没有办法强制重新格式化正在发送的消息?
- 您有更好的方法吗?
最后我发现通过在 Transformer 对象中使用这些属性,您可以获得良好缩进的输出:
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();
// Set formatting
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Source sc = soapMessage.getSOAPPart().getContent();
OutputStream streamOut = new FileOutputStream(new File(changeFileFolder, "soapRequest.xml"));
StreamResult result = new StreamResult(streamOut);
tf.transform(sc, result);
我是一名优秀的程序员,十分优秀!