How to add raw XML text to a SOAPBody element

I have the XML text that the application creates and I need to wrap a SOAP envelope around it and then make a web service call.

The following code creates a wrapper, but I do not know how to add existing XML data to a 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 tried body.addTextNode() , but it adds the content this way < , and others get the escape code.

+5
source share
2 answers

The following adds 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 logic convertStringToDocument() from this post .

+6
source

You need to tell the XML serializer to not parse and delete the contents of SOAPBody as XML. You can do this by including XML inside <![CDATA[]]>

  String rawXml = "<![CDATA[<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(); SOAPElement se = body.addTextNode(rawXml); System.out.println(body.getTextContent()); 

EDIT

 <some-data><some-data-item>1</some-data-item></some-data> 

This is the conclusion.

 System.out.println(body.getTextContent()); 
-1
source

All Articles