background image

DocumentBuilderFactory

<< Adding Content to the SOAPPart Object | Adding a Document to the SOAP Body >>
<< Adding Content to the SOAPPart Object | Adding a Document to the SOAP Body >>
A
DDING
C
ONTENT TO THE
SOAPP
ART
O
BJECT
135
To add a file directly to the
SOAPPart
object, you use a
javax.xml.trans-
form.Source
object from JAXP (the Java API for XML Processing). There are
three types of
Source
objects:
SAXSource
,
DOMSource
, and
StreamSource
. A
StreamSource
object holds an XML document in text form.
SAXSource
and
DOMSource
objects hold content along with the instructions for transforming the
content into an XML document.
The following code fragment uses the JAXP API to build a
DOMSource
object
that is passed to the
SOAPPart.setContent
method. The first three lines of code
get a
DocumentBuilderFactory
object and use it to create the
Document-
Builder
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
SOAPMes-
sage
object
message
) and set the new
Document
object as its content. The
SOAP-
Part.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 (page
136) and Adding Attachments (page 137).