Java Reference
In-Depth Information
NodeList reference that is empty, not null . You call the getChildNodes() method to obtain a list of child
nodes for any node type that can have them.
The NodeList interface declares just two methods: The getLength() method returns the number of
nodes in the list as type int , and the item() method returns a Node reference to the object at index position
in the list specified by the argument of type int .
You can use these methods to iterate through the child elements of the root element, perhaps like this:
Node[] nodes = new Node[children.getLength()];
for(int i = 0 ; i < nodes.getLength() ; ++i) {
nodes[i] = children.item(i);
}
You allocate sufficient elements in the nodes array to accommodate the number of child nodes and then
populate the array in the for loop.
Node Types
Of course, you will normally be interested in the specific types of nodes that are returned, so you will want
to extract them as specific types, or at least determine what they are before processing them. This is not
difficult. One possibility is to test the type of any node using the instanceof operator. Here's one way you
could extract just the child nodes that are of type Element and store them in a vector container:
Vector<Element> elements = new Vector<>();
Node node = null;
for(int i = 0 ; i < nodes.getLength() ; ++i) {
node = children.item(i);
if(node instanceof Element) {
elements.add(node);
}
}
Another possibility is provided by the getNodeType() method that is declared in the Node interface. This
method returns a value of type short that is one of the following constants that are defined in the Node in-
terface:
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
DOCUMENT_FRAGMENT_NODE
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
DOCUMENT_POSITION_PRECEDING
DOCUMENT_POSITION_FOLLOWING
DOCUMENT_POSITION_CONTAINED_BY
DOCUMENT_POSITION_CONTAINS
DOCUMENT_POSITION_DISCONNECTED
CDATA_SECTION_NODE
ENTITY_REFERENCE_NODE
ENTITY_NODE
Search WWH ::




Custom Search