Java Reference
In-Depth Information
Adding an Attribute to an Element
Problem
You want to add an attribute to an element in the body of your SOAP message.
Solution
Create a
QName
for your attribute and add it to the desired element using the
SOAPEle-
ment.addAttribute
method.
Discussion
When you create the
QName
for the attribute, you don't need to give it the namespace because
it will inherit from its enclosing parent. Just create it using the local part, specifying the name
of your attribute as the
QName
. Then give it a value as the second argument to the
addAttrib-
ute
method. That's really all there is to it.
Example 5-8
shows the complete listing that adds an attribute to a message element.
Example5-8.Adding an attribute to an element
package addAttribute;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPElement;
public class SAAJCreateAttribute {
public static void main(String args[]) {
try {
//Create a SOAPMessage
MessageFactory messageFactory =
MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPEnvelope env = message.getSOAPPart().getEnvelope();
SOAPBody body = env.getBody();
//Create a SOAPBodyElement