Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add raw XML text to SOAPBody element

Tags:

java

xml

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.

like image 746
Evandro Pomatti Avatar asked Apr 29 '15 12:04

Evandro Pomatti


1 Answers

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.

like image 200
Evandro Pomatti Avatar answered Sep 28 '22 00:09

Evandro Pomatti