我正在使用带有 Java 7 的 SAAJ 来创建和发送 SOAP 消息。除了身体,我什么都准备好了。我需要在没有任何格式错误的情况下将 XML 文件的内容放入 SOAP 消息的正文中。我尝试过使用 DOM 文档,我尝试使用扫描仪逐行读取它并手动添加它,但它们都不起作用。DOM 文档解决方案最终只是删除了消息的标题和正文,而我的其他解决方案分别用“<”和“>”覆盖了“<”和“>”字符。我已经尝试使用 String.replaceWith() 来破解它,但是随着 SOAP 消息的发送,这种变化正在发生。有谁知道我可以如何实现这一点,而不必编写一个巨大的解析器来从 xml 文件创建 SAAJ 对象?谢谢。
问问题
3270 次
2 回答
2
这个简单的测试对我有用:
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>
于 2014-07-07T21:19:53.660 回答
0
你也可以使用
SOAPMessage message = getSoapMessageFromString("<a><b><c>hello</c><d test='attrib'>foo</d></b>blablabla</a>");
private static SOAPMessage getSoapMessageFromString(String xml)
throws SOAPException, IOException {
MessageFactory factory = MessageFactory.newInstance();
// Create a new message object with default MIME headers and the data
// from the XML string we passed in
SOAPMessage message = factory
.createMessage(
new MimeHeaders(),
new ByteArrayInputStream(xml.getBytes(Charset
.forName("UTF-8"))));
return message;
}
如果您已经将 xml 文本解析为字符串对象并且不关心解析或验证它。
于 2015-02-27T21:50:42.520 回答