Java Reference
In-Depth Information
the
getAttributes()
method for any node type, and it returns
null
if an element has no attributes. Thus,
you could omit the test for the element type in the
if
condition, and the code works just as well.
The
NamedNodeMap
interface declares the following methods for retrieving nodes from the collection:
•
Node item(int index)
: Returns the node at position
index
.
•
int getLength()
: Returns the number of
Node
references in the collection.
•
Node getNamedItem(String name)
: Returns the node with the node name
name
.
•
Node getNamedItemNS(String uri,String localName)
: Returns the node with the name
loc-
alName
in the namespace at
uri
.
Obviously the last two methods apply when you know what attributes to expect. You can apply the first two
methods to iterate through the collection of attributes in a
NamedNodeMap
:
if(node.hasAttributes()) {
NamedNodeMap attrs = node.getAttributes();
for(int i = 0 ; i < attrs.getLength() ; ++i) {
Attr attribute = (Attr)attrs.item(i);
// Process the attribute...
}
}
You now are in a position to obtain each of the attributes for an element as a reference of type
Attr
. To
get at the attribute name and value you call the
getName()
and
getValue()
methods declared in the
Attr
interface, respectively, both of which return a value of type
String
. You can put that into practice in another
example.
TRY IT OUT: Listing Elements with Attributes
You can modify the
listNodes()
method in the previous example to include attributes with the ele-
ments. Here's the revised version:
static void listNodes(Node node) {
System.out.println(indent + " Node: " + nodeName);
short type =node.getNodeType();
System.out.println(indent + " Node Type: " + nodeType(type));
if(type == TEXT_NODE){
System.out.println(indent + " Content is: " +
((Text)node).getWholeText());
} else if(node.hasAttributes()) {
System.out.println(indent+" Element Attributes are:");
NamedNodeMap attrs = node.getAttributes();
//...get the
attributes
for(int i = 0 ; i < attrs.getLength() ; ++i) {
Attr attribute = (Attr)attrs.item(i);
// Get an
attribute
System.out.println(indent + " " + attribute.getName() +
" = " + attribute.getValue());