background image

Adding Content to the Body

<< Accessing Elements of a Message | QName and SOAPElement >>
<< Accessing Elements of a Message | QName and SOAPElement >>
C
REATING AND
S
ENDING A
S
IMPLE
M
ESSAGE
127
Adding Content to the Body
The
SOAPBody
object contains either content or a fault. To add content to the
body, you normally create one or more
SOAPBodyElement
objects to hold the
content. You can also add subelements to the
SOAPBodyElement
objects by using
the
addChildElement
method. For each element or child element, you add con-
tent by using the
addTextNode
method.
When you create any new element, you also need to create an associated
javax.xml.namespace.QName
object so that it is uniquely identified.
Note: You can use
Name
objects instead of
QName
objects.
Name
objects are specific
to the SAAJ API, and you create them using either
SOAPEnvelope
methods or
SOAPFactory
methods. However, the
Name
interface may be deprecated at a future
release.
The
SOAPFactory
class also lets you create XML elements when you are not creat-
ing an entire message or do not have access to a complete
SOAPMessage
object. For
example, JAX-RPC implementations often work with XML fragments rather than
complete
SOAPMessage
objects. Consequently, they do not have access to a
SOAPEn-
velope
object, and this makes using a
SOAPFactory
object to create
Name
objects
very useful. In addition to a method for creating
Name
objects, the
SOAPFactory
class provides methods for creating
Detail
objects and SOAP fragments. You will
find an explanation of
Detail
objects in Overview of SOAP Faults (page 146) and
Creating and Populating a SOAPFault Object (page 147).
QName
objects associated with
SOAPBodyElement
or
SOAPHeaderElement
objects must be fully qualified; that is, they must be created with a namespace
URI, a local part, and a namespace prefix. Specifying a namespace for an ele-
ment makes clear which one is meant if more than one element has the same
local name.
The following code fragment retrieves the
SOAPBody
object
body
from
message
,
constructs a
QName
object for the element to be added, and adds a new
SOAP-
BodyElement
object to
body
.
SOAPBody body = message.getSOAPBody();
QName bodyName = new QName("http://wombat.ztrade.com",
"GetLastTradePrice", "m");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
At this point,
body
contains a
SOAPBodyElement
object identified by the
QName
object
bodyName
, but there is still no content in
bodyElement
. Assuming that