gpt4 book ai didi

java - 使用 StreamResult 打印 SOAP 消息时或修改其 DOM 结构后出现未格式化的输出

转载 作者:太空宇宙 更新时间:2023-11-04 14:31:44 26 4
gpt4 key购买 nike

我想输出一些 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>

另一方面,当我使用 DomSourceStreamResult 检查响应正文时,消息内容显示在一行中(所有它):

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);

关于java - 使用 StreamResult 打印 SOAP 消息时或修改其 DOM 结构后出现未格式化的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com