XML Parser


All modern browsers have a built-in XML parser.

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


Parse an XML Document

The following code fragment parses an XML document into an XML DOM object:

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

Parse an XML String

The following code fragment parses an XML string into an XML DOM object:

txt="<bookstore><book>";
txt=txt+"<title>Everyday Italian</title>";
txt=txt+"<author>Giada De Laurentiis</author>";
txt=txt+"<year>2005</year>";
txt=txt+"</book></bookstore>";

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.



SHARE THIS PAGE

COLOR PICKER

colorpicker





Search w3schools.com:

Translate w3schools.com: