Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XML DOM – Traversing the Node Tree

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 all its child nodes, and displays their names and values:

Example

<!DOCTYPE html>
<html>
<body>
<p id="demo" p>
<script var x,i,xmlDoc>

;

var

txt

=

"

"

;

var

text

=

"

"

"

Everyday Italian

"

"

Giada De Laurentiis

"

"

2005

"

"

"

;

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:

  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 text nodes