background image

The SOAPElement Interface

<< Accessing an AttachmentPart Object | Header Attributes >>
<< Accessing an AttachmentPart Object | Header Attributes >>

The SOAPElement Interface

The SOAPElement interface provides methods for adding an attribute, for getting the value of an
attribute, and for removing an attribute. For example, in the following code fragment, the
attribute named id is added to the SOAPElement object person. Because person is a
SOAPElement
object rather than a SOAPBodyElement object or SOAPHeaderElement object, it is
legal for its QName object to contain only a local name.
QName attributeName = new QName(
"id");
person.addAttribute(attributeName,
"Person7");
These lines of code will generate the first line in the following XML fragment.
<person id=
"Person7">
...
</person>
The following line of code retrieves the value of the attribute whose name is id.
String attributeValue = person.getAttributeValue(attributeName);
If you had added two or more attributes to person, the preceding line of code would have
returned only the value for the attribute named id. If you wanted to retrieve the values for all the
attributes for person, you would use the method getAllAttributes, which returns an iterator
over all the values. The following lines of code retrieve and print each value on a separate line
until there are no more attribute values. Note that the Iterator.next method returns a Java
Object
, which is cast to a QName object so that it can be assigned to the QName object
attributeName
. (The examples in
"DOM and DOMSource Examples" on page 617
use code
similar to this.)
Iterator iterator = person.getAllAttributesAsQNames();
while (iterator.hasNext()){
QName attributeName = (QName) iterator.next();
System.out.println(
"Attribute name is " + attributeName.toString());
System.out.println(
"Attribute value is " +
element.getAttributeValue(attributeName));
}
The following line of code removes the attribute named id from person. The variable
successful
will be true if the attribute was removed successfully.
boolean successful = person.removeAttribute(attributeName);
In this section you have seen how to add, retrieve, and remove attributes. This information is
general in that it applies to any element. The next section discusses attributes that can be added
only to header elements.
SAAJ Tutorial
The Java EE 5 Tutorial · September 2007
604