I have an XML text that is generated by the application, and I need to wrap a SOAP envelope around it and later make the web service call.
The following code builds up the envelope, but I don't know how the add the existing XML data into the SOAPBody
element.
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();
I have tried body.addTextNode()
but it adds content so <
and others get escaped.
The following adds the XML as a Document:
Document document = convertStringToDocument(rawXml);
body.addDocument(document);
Document creation:
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;
}
I took the convertStringToDocument()
logic from this post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With