我有一个由应用程序生成的 XML 文本,我需要将它包裹在一个 SOAP 信封中,然后进行 Web 服务调用。
下面的代码构建了信封,但我不知道如何将现有的 XML 数据添加到 SOAPBody
中元素。
String rawXml = "<some-data><some-data-item>1</some-data-item></some-data>";
// Start the API
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();
SOAPEnvelope env = part.getEnvelope();
// Get the body. How do I add the raw xml directly into the body?
SOAPBody body = env.getBody();
我试过了body.addTextNode()
但它添加了内容所以<
其他人逃脱了。
最佳答案
以下将 XML 添加为文档:
Document document = convertStringToDocument(rawXml);
body.addDocument(document);
文档创建:
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
我从 this post 中获取了 convertStringToDocument()
逻辑.
关于java - 如何将原始 XML 文本添加到 SOAPBody 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29944025/