XML DOM traversing the node tree

Traverse (Traverse) means to loop or move through the node tree.

Example

The following example uses an XML file books.xml.

Function loadXMLString(), located in external JavaScript, used to load XML files.

Traversing a node tree
Loop through all child nodes of the <book> element.

Traversing the node tree

You often need to loop through XML documents, such as: when you need to extract the value of each element.

This process is called 'traversing the node tree'.

The following example loops through all child nodes of <book> and displays their names and values:

<html>
<head>
<script type="text/javascript" src="loadxmlstring.js"></script>
</head>
<body>
<script type="text/javascript">
text="<book>";
text=text+"<title>Harry Potter</title>";
text=text+"<author>J K. Rowling</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("<br />");
}
</script>
</body>
</html>

Output:

title: Harry Potter
author: J K. Rowling
year: 2005

Example Explanation:

  • loadXMLString() Load the XML string into xmlDoc
  • Get the child nodes of the root element
  • Output the name of each child node, as well as the node value of text nodes

TIY