XML DOM tutoria...LOGIN
XML DOM tutorial
author:php.cn  update time:2022-04-13 15:27:56

DOM traversal


XML DOM Traverse the node tree


Traverse means looping or moving in the node tree.


Traverse the node tree

Often you want to loop over 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>
<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("<br>");
  }
</script>
</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

Output:

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

Example explanation:

  1. loadXMLString() loads 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


php.cn