Reputation: 2546
I´d like to output the content of a some SOAPMessage
(a request and a response in this case), let´s say to the standard output, and I am having issues to see the content in a well-formatted way:
// 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);
Here, the only part that is well formatted is the part loaded from the XML, the rest is displayed in a single line!
<?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>
On the other hand, when I inspect the body of the response using a DomSource
and a StreamResult
the content of the message is displayed in a single line (all of it):
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);
My questions are:
Marshaller.JAXB_FORMATTED_OUTPUT
property)?Upvotes: 2
Views: 943
Reputation: 2546
Finally I found out that by using these properties in the Transformer object, you can get a well indented output:
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);
Upvotes: 2