我使用 SAAJ 和 Java 7 来创建和发送 SOAP 消息。除了 body ,我已经把一切都准备好了。我需要将 XML 文件的内容放入 SOAP 消息的正文中,且不出现任何格式错误。我尝试过使用 DOM 文档,尝试使用扫描仪逐行读取它并手动添加它,但它们都不起作用。 DOM 文档解决方案最终只是删除了消息的标题和正文,而我的另一个解决方案则分别用“<”和“">”覆盖“<”和“">”字符。我尝试使用 String.replaceWith() 来破解此问题,但更改是在发送 SOAP 消息时发生的。有谁知道我如何能够完成此任务,而无需编写一个巨大的解析器来从 xml 文件创建 SAAJ 对象?谢谢。
最佳答案
这个简单的测试对我有用:
import org.junit.*;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
/**
*
* @author gpeche
*/
public class SAAJTest {
@Test
public void testAddDocument() throws Exception {
String xml = "<a><b><c>hello</c><d test='attrib'>foo</d></b>blablabla</a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
SOAPMessage message = MessageFactory.newInstance().createMessage();
SOAPBody body = message.getSOAPBody();
body.addDocument(doc);
message.saveChanges();
message.writeTo(System.out);
System.out.println();
}
}
输出:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><a><b><c>hola</c><d test="attrib">foo</d></b>blablabla</a></SOAP-ENV:Body></SOAP-ENV:Envelope>
关于java - 我需要将 XML 文件附加到在 Java 7 中使用 SAAJ 的 SOAP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24619536/