Easy Tutorial
❮ Met Element Comparedocumentposition Met Text Appenddata ❯

XML DOM Parser

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

The parser converts XML into a JavaScript-accessible object (XML DOM).

XML Parser

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

However, before accessing and manipulating the XML document, it must be loaded into the XML DOM object.

The XML parser reads the XML and converts it into an XML DOM object, which can then be accessed using 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 code
  xhttp=new XMLHttpRequest();
}
else
{
  // IE6, IE5 code
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

Code Explanation:

Loading 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); 
}

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 webpage and the XML file must be on the same server.

All XML files opened in the examples on tutorialpro.org are located on the tutorialpro.org domain.

If you want to use the above examples on your webpage, the XML files must be on your own server.

❮ Met Element Comparedocumentposition Met Text Appenddata ❯