background image

QName and SOAPElement

<< Adding Content to the Body | SOAP envelope element >>
<< Adding Content to the Body | SOAP envelope element >>
128
SOAP
WITH
A
TTACHMENTS
API
FOR
J
AVA
you want to get a quote for the stock of Sun Microsystems, Inc., you need to cre-
ate a child element for the symbol using the
addChildElement
method. Then
you need to give it the stock symbol using the
addTextNode
method. The
QName
object for the new
SOAPElement
object
symbol
is initialized with only a local
name because child elements inherit the prefix and URI from the parent element.
QName name = new QName("symbol");
SOAPElement symbol = bodyElement.addChildElement(name);
symbol.addTextNode("SUNW");
You might recall that the headers and content in a
SOAPPart
object must be in
XML format. The SAAJ API takes care of this for you, building the appropriate
XML constructs automatically when you call methods such as
addBodyElement
,
addChildElement
, and
addTextNode
. Note that you can call the method
addTextNode
only on an element such as
bodyElement
or any child elements
that are added to it. You cannot call
addTextNode
on a
SOAPHeader
or
SOAPBody
object because they contain elements and not text.
The content that you have just added to your
SOAPBody
object will look like the
following when it is sent over the wire:
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<m:GetLastTradePrice xmlns:m="http://wombat.ztrade.com">
<symbol>SUNW</symbol>
</m:GetLastTradePrice>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Let's examine this XML excerpt line by line to see how it relates to your SAAJ
code. Note that an XML parser does not care about indentations, but they are
generally used to indicate element levels and thereby make it easier for a human
reader to understand.
Here is the SAAJ code:
SOAPMessage message = messageFactory.createMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPBody body = message.getSOAPBody();