May 27, 2021 XML
All modern browsers have built-in XML parsers.
The XML parser converts the XML document to an XML DOM object - an object that can be operated by JavaScript.
The following snippets parse the XML document into the 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","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
The following snippet parses the XML string into the 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 XML strings, while other browsers use DOMParser objects.
For security reasons, modern browsers do not allow cross-domain access.
This means that the web page and the XML file it is trying to load must be on the same server.
In the next section, you'll learn how to access XML DOM objects and get your data back.