XML DOM - Traversing the node tree
May 27, 2021
XML DOM
Table of contents
XML DOM
traverses the node tree
You often need to loop through XML documents, for example, when you need to extract the value of each element, a process called traversing the node tree.
Traverse means looping or moving through the node tree.
Traverse the node tree
Usually you want to loop XML documents, for example, when you need to extract the value of each element.
This is called traversing the node tree.
The following example traverses all the child nodes of the slt;book; and displays their names and values:
<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 out . . .
Example explanation:
-
LoadXMLString()
loads the XML string into xmlDoc
-
Gets the child node of the root element
-
Outputs the node name of each child node and the node value of the text node
That's all about the DOM traversing the node tree, and by traversing, you can get the names and values of the child nodes!