Latest web development tutorials

XML DOM - traversing the node tree

Traversal (Traverse) means cyclic or mobile node in the tree.


Traversing the node tree

Typically, you want to cycle XML documents, such as: when you need to extract the value of each element.

This is called "traversing the node tree."

The following examples traverses <book> all the child nodes and displays their names and values:

Examples

<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
text="<book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book>";

xmlDoc=loadXMLString(text);

// documentElement always represents the root node
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("
");
}
</script>
</body>
</html>

Output:

title: Everyday Italian
author: Giada De Laurentiis
year: 2005

try it"

Examples explain:

  1. loadXMLString () the XML string into xmlDoc
  2. Getting child nodes of the root element
  3. Value of the output node node name of each child node and a text node