Java Reference
In-Depth Information
nodes),
Node getFirstChild()
(return the node's first child), and
Node
getLastChild()
(return the node's last child). For nodes with multiple children,
you'll find the
NodeList getChildNodes()
method to be handy. This method
returnsan
org.w3c.dom.NodeList
instancewhose
int getLength()
method
returnsthenumberofnodesinthelist,andwhose
Node item(int index)
method
returnsthenodeatthe
index
thpositioninthelist(ornullwhen
index
'svalueisnot
valid—it's less than 0 or greater than or equal to
getLength()
's value).
Node
declaresfourmethodsformodifyingthetreebyinserting,removing,replacing,
andappendingchildnodes.The
Node insertBefore(Node newChild, Node
refChild)
method inserts
newChild
before the existing node specified by
re-
fChild
and returns
newChild
,
Node removeChild(Node oldChild)
re-
moves the child node identified by
oldChild
from the tree and returns
oldChild
,
Node replaceChild(Node newChild, Node oldChild)
replaces
oldChild
with
newChild
and returns
oldChild
, and
Node ap-
pendChild(Node newChild)
adds
newChild
to the end of the current node's
child nodes and returns
newChild
.
Finally,
Node
declares several utility methods, including
Node
cloneNode(boolean deep)
(create and return a duplicate of the current node,
recursively cloning its subtree when
true
is passed to
deep
),and
void normal-
ize()
(descendthetreefromthegivennodeandmergealladjacenttextnodes,delet-
ing those text nodes that are empty).
Tip
To obtain an element node's attributes, first call
Node
's
NamedNodeMap
getAttributes()
method. This method returns an
org.w3c.dom.NamedNodeMap
implementation when the node represents an ele-
ment; otherwise, it returns null. In addition to declaring methods for accessing these
nodesbyname(e.g.,
Node getNamedItem(String name)
),
NamedNodeMap
declares
int getLength()
and
Node item(int index)
methodsforreturn-
ingallattributenodesby
index
.Youwouldthenobtainthe
Node
'snamebycallinga
method such as
getNodeName()
.
As well as inheriting
Node
's constants and methods,
Document
declares its own
methods. For example, you can call
Document
's
String getXmlEncoding()
,
boolean getXmlStandalone()
, and
String getXmlVersion()
methods
to return the XML declaration's
encoding
,
standalone
, and
version
attribute
values, respectively.