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

XML DOM Loading Functions

XML DOM Loading Functions


The code for loading an XML document can be stored in a function.


The loadXMLDoc() function

To make the code from the previous page easy to maintain (checking for old browsers), it should be written as a function:

Code in the loadxmldoc.js file:

function

loadXMLDoc

(

dname

)

{

if

(

window

.

XMLHttpRequest

)

{

xhttp

=

new

XMLHttpRequest

(

)

;

}

else

{

xhttp

=

new

ActiveXObject

(

"

Microsoft.XMLHTTP

"

)

;

}

xhttp

.

open

(

"

GET

"

,

dname

,

false

)

;

xhttp

.

send

(

)

;

return

xhttp

.

responseXML

;

}

The function above can be stored in the section of an HTML page and called from a script in the page.

lampThe function described above is used in all XML document examples in this tutorial!


External JavaScript for loadXMLDoc()

To make the above code easier to maintain and to ensure the same code is used on all pages, we store the function in an external file.

The file is named "loadxmldoc.js" and is loaded in the head section of the HTML page. Then, a script in the page calls the loadXMLDoc() function.

The following example uses the loadXMLDoc() function to load books.xml:

Example

<html>
<head>
<script src="loadxmldoc.js" script head>
<body>
<script>

xmlDoc=loadXMLDoc("books.xml"); code goes here.....

script

body

html

Try it »

How to get data from an XML file will be explained in the next chapter.


The loadXMLString() function

To make the code from the previous page easy to maintain (checking for old browsers), it should be written as a function:

Code in the loadxmlstring.js file:

function

loadXMLString

(

txt

)

{

if

(

window

.

DOMParser

)

{

parser

=

new

DOMParser

(

)

;

xmlDoc

=

parser

.

parseFromString

(

txt

,

"

text/xml

"

)

;

}

else

{

//

Internet Explorer

xmlDoc

=

new

ActiveXObject

(

"

Microsoft.XMLDOM

"

)

;

xmlDoc

.

async

=

false

;

xmlDoc

.

loadXML

(

txt

)

;

}

return

xmlDoc

;

}

The function above can be stored in the section of an HTML page and called from a script in the page.

lampThe function described above is used in all XML string examples in this tutorial!


External JavaScript for loadXMLString()

We have stored the loadXMLString() function in a file named "loadxmlstring.js".

Example

<html>
<head>
<script src="loadxmlstring.js" script head>
<body>
<script text="" text=text"">

;

text

=

text

"

Everyday Italian

"

;

text

=

text

"

Giada De Laurentiis

"

;

text

=

text

"

2005

"

;

text

=

text

"

"

;

text

=

text

"

"

;

xmlDoc

=

loadXMLString

(

text

)

;

code

goes

here

.....

script

body

html

Try it »