View RSS Feed

Java XML

DOM Elements, Child Elements, and the Node Interface

Rate this Entry
by , 04-27-2012 at 05:11 PM (2897 Views)
The root element has children which can be elements, comments, processing instructions, characters etc. You get the children of an element like this:
Java Code:
NodeList nodes = element.getChildNodes();

for(int i=0; i<nodes.getLength(); i++){
  Node node = nodes.item(i);

  if(node instanceof Element){
    //a child element to process
    Element child = (Element) node;
    String attribute = child.getAttribute("width");
  }
}
The getChildNodes() method returns a NodeList object, which is a list of Node elements. TheNode interface is a superinterface for pretty much all of the different node types in DOM. This means, that the Document interface inherits from (extends) Node, the Element interface extendsNode, the Attr (attribute) interface extends Node etc.
The fact that Node is the super-interface of all the node-interfaces in DOM means that you will sometimes have to look in the Node interface for the methods you need, like the methodgetChildNodes(). This is something to be aware of, when trying to iterate through a Documentgraph.

Submit "DOM Elements, Child Elements, and the Node Interface" to Facebook Submit "DOM Elements, Child Elements, and the Node Interface" to Digg Submit "DOM Elements, Child Elements, and the Node Interface" to del.icio.us Submit "DOM Elements, Child Elements, and the Node Interface" to StumbleUpon Submit "DOM Elements, Child Elements, and the Node Interface" to Google

Tags: dom elements Add / Edit Tags
Categories
DOM

Comments