XML DOM Traverse node tree


Traverse means to loop or move through the node tree.


Traverse node tree

Often you want to loop through an XML document, for example: when you need to extract the value of each element.

This is called "traversing the node tree".

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

Example

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script>
var x, i ,xmlDoc; var txt = ""; var text = "<book>" + "<title>Everyday Italian</title>" + "<author>Giada De Laurentiis</author>" + "<year>2005</year>" + "</book>"; parser = new DOMParser(); xmlDoc = parser.parseFromString(text,"text/xml"); //documentElement represents the root node x = xmlDoc.documentElement.childNodes; for (i = 0; i < x.length ;i++) { txt += x[i].nodeName + ": " + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt;
</script> </body> </html>

Output:

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

Try it Yourself »

Example explanation:

  1. Load the XML string into xmlDoc.
  2. Get the child nodes of the root element
  3. Output the node name of each child node and the node value of the text node.

other extensions