background image

getAttributeValue Method

<< Accessing an AttachmentPart Object | Header Attributes >>
<< Accessing an AttachmentPart Object | Header Attributes >>
140
SOAP
WITH
A
TTACHMENTS
API
FOR
J
AVA
BodyElement
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
DOMExample.java
and
DOMSrcExample.java (page 162) 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 dis-
cusses attributes that can be added only to header elements.