Java Reference
In-Depth Information
item(int index)
Returns the Node reference at index position
index .
getLength()
Returns the number of Node references in the
collection as type int .
getNamedItem(String name)
Returns the Node reference with the node name
name .
getNamedItemNS(String uri,
String localName)
Returns the Node reference with the name
localName in the namespace at uri .
Obviously the last two methods apply when you know what attributes to expect. We can apply the first
two methods to iterate through the collection of attributes in a NamedNodeMap :
if(node instanceof Element && node.hasAttributes()) {
NamedNodeMap attrs = node.getAttributes();
for(int i = 0 ; i<attrs.getLength() ; i++) {
Attr attribute = (Attr)attrs.item(i); // Process the attribute...
}
} else { // Process the element without attributes
}
We 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 we call the getName() and getValue() methods declared in the
Attr interface respectively, both of which return a value of type String .
Try It Out - Listing Elements with Attributes
We can modify the listNodes() method in the previous example to include attributes with the
elements. Here's the revised version:
static void listNodes(Node node) {
String nodeName = node.getNodeName();
System.out.println(indent+nodeName+" Node, type is "
+node.getClass().getName()+":");
System.out.println(indent+" "+node);
if(node instanceof Element && 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());
}
}
NodeList list = node.getChildNodes(); // Get the list of child nodes
if(list.getLength() > 0) { // As long as there are some...
System.out.println(indent+"Child Nodes of "+nodeName+" are:");
for(int i = 0 ; i<list.getLength() ; i++)// ...list them & their children...
listNodes(list.item(i),indent+" "); // by calling listNodes()
Search WWH ::




Custom Search