Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XML DOM parser


May 27, 2021 XML DOM


Table of contents


XML DOM parser

This section will introduce you to XML parsers, which are built into most browsers.

Most browsers have built-in XML parsers for reading and operating XML.

The parser converts XML to JavaScript accessable objects (XML DOMs).


XML parser

XML DOM contains methods (functions) for traversing the XML tree to access, insert, and delete nodes.

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

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

Most browsers have a built-in XML parser.


Load the XML document

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

if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

Try it out . . .

Code interpretation:

  • Create an XMLHTTP object
  • Open the XMLHTTP object
  • Send an XML HTTP request to the server
  • Set the response to an XML DOM object

Load the XML string

The following code loads and parses an XML string:

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 out . . .

Note: Internet Explorer uses the loadXML() method to parse XML strings, while other browsers use DOMParser objects.


Cross-domain access

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

This means that the web page, as well as the XML file, must be on the same server as the attempt to load.

All open XML files in the instance on W3CSchool are on the W3CSchool domain.

If you want to use the instance above on your web page, the XML file you loaded must be on your own server.

Related tutorials

JavaScript tutorial