XML DOM Traversing the Node Tree
Traversing means looping or moving through the node tree.
Traverse the Node Tree
Usually 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
Example
<!DOCTYPE html><html>
<body>
<p id="demo" p>
<script var x,i,xmlDoc>;
var
txt
=
"
"
;
var
text
=
"
"
"
"
"
"
"
"
"
"
;
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
"
"
;
}
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
txt
;
script
body
html
Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
Try it »
Example explanation:
- Load the XML string into xmlDoc
- Get the child nodes of the root element
- Output the node name of each child node and the node value of text nodes