XML Parser

« Previous Chapter Next Chapter »

All modern browsers have a built-in XML parser.

An XML parser converts an XML document into a XML DOM object - which can then be manipulated with a JavaScript.

Parse an XML Document

The Below code fragment parses an XML document into a XML DOM object:

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","demofile.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;


Parse an XML String

The Below code fragment parses an XML string into a XML DOM object:

txt="<friendsdata><book>";
txt=txt+"<title>A men</title>";
txt=txt+"<author>Karon</author>";
txt=txt+"<year>1992</year>";
txt=txt+"</book></friendsdata>";

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

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

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means, that both the web page and the XML file it tries to load, must be located on the same server.

The XML DOM

In the next chapter you will learn how to access and retrieve data from the XML DOM object.


« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!