background image

Adding a Document to the SOAP Body

<< Adding Content to the SOAPPart Object | Adding Attachments >>
<< Adding Content to the SOAPPart Object | Adding Attachments >>

Adding a Document to the SOAP Body

object and use it to create the DocumentBuilder object builder. Because SOAP messages use
namespaces, you should set the NamespaceAware property for the factory to true. Then builder
parses the content file to produce a Document object.
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document document = builder.parse(
"file:///music/order/soap.xml");
DOMSource domSource = new DOMSource(document);
The following two lines of code access the SOAPPart object (using the SOAPMessage object
message
) and set the new Document object as its content. The SOAPPart.setContent method
not only sets content for the SOAPBody object but also sets the appropriate header for the
SOAPHeader
object.
SOAPPart soapPart = message.getSOAPPart();
soapPart.setContent(domSource);
The XML file you use to set the content of the SOAPPart object must include Envelope and Body
elements:
<SOAP-ENV:Envelope
xmlns=
"http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
...
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
You will see other ways to add content to a message in the sections
"Adding a Document to the
SOAP Body" on page 600
and
"Adding Attachments" on page 601
.
Adding a Document to the SOAP Body
In addition to setting the content of the entire SOAP message to that of a DOMSource object, you
can add a DOM document directly to the body of the message. This capability means that you
do not have to create a javax.xml.transform.Source object. After you parse the document,
you can add it directly to the message body:
SOAPBody body = message.getSOAPBody();
SOAPBodyElement docElement = body.addDocument(document);
SAAJ Tutorial
The Java EE 5 Tutorial · September 2007
600