Java Reference
In-Depth Information
Each of these interfaces declares its own set of methods and inherits the method declared in the Node
interface. Every XML document will be modeled as a hierarchy of nodes that will be accessible as one
or other of the interface types in the table above. At the top of the node hierarchy for a document will
be the Document node that is returned by the parse() method. Each type of node may or may not
have child nodes in the document hierarchy, and those that do can only have certain types of child
node. The types of nodes in a document that can have children are as follows:
Node Type
Possible Children
Document
Element (only 1), DocumentType (only 1), Comment ,
ProcessingInstruction
Element
Element , Text , Comment , CDATASection , EntityReference ,
ProcessingInstruction
Attr
Text , EntityReference
Entity
Element , Text , Comment , CDATASection , EntityReference ,
ProcessingInstruction
EntityReference
Element , Text , Comment , CDATASection , EntityReference ,
ProcessingInstruction
Of course, what each node may have as children follows from the XML specification, not just the DOM
specification. There is one other type of node that extends the Node interface - DocumentFragment .
This is not formally part of a document in the sense that a node of this type is a programming
convenience. It is used to house a fragment of a document - a sub-tree of elements - for use when
moving fragments of a document around, for instance, so it provides a similar function to a Document
node but with less overhead. A DocumentFragment node can have the same range of child nodes as
an Element node.
The starting point for exploring the entire document tree is the root element for the document. We can
obtain a reference to an object that encapsulates the root element by calling the
getDocumentElement() method for the Document object:
Element root = xmlDoc.getDocumentElement();
This method returns the root element for the document as type Element . You can also get the node
corresponding to the DOCTYPE declaration as type DocumentType like this:
DocumentType doctype = xmlDoc.getDoctype();
The next step is to obtain the child nodes for the root element. We can use the getChildNodes()
method that is defined in the Node interface for this. This method returns a NodeList reference that
encapsulates all the child elements for that element. You can call this method for any node that has
children, including the Document node if you wish. We can therefore obtain the child elements for the
root element with the following statement:
NodeList children = root.getChildNodes();
Search WWH ::




Custom Search