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

XML DOM Parsers

XML DOM Parsers


Most browsers have a built-in XML parser for reading and manipulating XML.

The parser converts XML into objects accessible by JavaScript (XML DOM).


XML Parser

The XML DOM contains methods (functions) for traversing the XML tree and accessing, inserting and deleting nodes.

However, before an XML document can be accessed and manipulated, it must be loaded into an XML DOM object.

The XML parser reads the XML and converts it into an XML DOM object so that it can be accessed with JavaScript.

Most browsers have a built-in XML parser.


Loading an XML document

The following JavaScript snippet loads an XML document ("books.xml"):

Example

if

(

window

.

XMLHttpRequest

)

{

//

IE7+, Firefox, Chrome, Opera, Safari browser execution code

xhttp

=

new

XMLHttpRequest

(

)

;

}

else

{

//

IE6, IE5 browser execution code

xhttp

=

new

ActiveXObject

(

"

Microsoft.XMLHTTP

"

)

;

}

xhttp

.

open

(

"

GET

"

,

"

books.xml

"

,

false

)

;

xhttp

.

send

(

)

;

xmlDoc

=

xhttp

.

responseXML

;

Try it »

Code Explanation:


Load an XML string

The following code loads and parses an XML string:

Example

if

(

window

.

DOMParser

)

{

parser

=

new

DOMParser

(

)

;

xmlDoc

=

parser

.

parseFromString

(

text

,

"

text/xml

"

)

;

}

else

{

//

Internet Explorer

xmlDoc

=

new

ActiveXObject

(

"

Microsoft.XMLDOM

"

)

;

xmlDoc

.

async

=

false

;

xmlDoc

.

loadXML

(

text

)

;

}

Try it »

**Note:** Internet Explorer uses the loadXML() method to parse an XML string, while other browsers use the DOMParser object.


Cross-domain access

For security reasons, modern browsers do not allow cross-domain access.

This means that the web page and the XML file must be located on the same server in order to load.

All XML files opened in the examples on Runoob Tutorial are located on the Runoob Tutorial domain.

If you want to use the above example on your own web page, the XML file you load must be located on your own server.