We can navigate between nodes with the use of their relationship to
each other:
parentNode
childNodes
nextSibling
previousSibling
firstChild
lastChild
Look at the XML file called bookdetails.xml which is in
XML DOM nodes page
The following image illustrate a part of the node tree and
the relationship between the nodes in the XML file above:
Note: Internet Explorer will skip white-space text
node that are generated between nodes (e.g. new-line
characters), while Mozilla will not. So, in the example below,
we have a function that checks the node type of a node when
using the firstChild, lastChild, nextSibling and previousSibling
properties.
Get the First Child of a Node
The following code fragment get the first child node of <bookstore>:
//check if the first node is an element node
function get_firstchild(n)
{
var x=n.firstChild;
while (x.nodeType!=1)
{
x=x.nextSibling;
}
return x;
}
xmlDoc=load("bookdetails.xml");
var y=get_firstchild(xmlDoc.documentElement);
document.write(y.nodeName);
O/P:
book
The function in the example above check the node type of
the first child node.
Element nodes has nodeType of 1, so if
the first child node is not an element node, it moves to the
next node, and checks if this node is an element node. This
continues until the first child node is found. This way, the result will be correct in both
Mozilla and Internet Explorer.
Get the Previous Sibling of a Node
The following code fragment get the previous sibling node of the first <author> element:
//check if the previous sibling node is an element node
function get_previoussibling(n)
{
var x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}xmlDoc=load("bookdetails.xml");
var x=xmlDoc.getElementsByTagName("author")[0];
var y=get_previoussibling(x);
document.write(y.nodeName);
O/P:
title
The function in the example above check the node type of
the previous sibling node.
If the previous sibling node is not
element node, it moves to the "next" previous sibling, and
checks if that node is an element node. This continues until the
previous sibling node is found.
This way, the result will be correct in both Mozilla
and Internet Explorer
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
Keywords:
xml document, xml file, xml parser, xmldom microsoft.xmldom, text node, xml dom attribute, document object model