XML Parser
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - an object that can be manipulated with JavaScript.
Parsing an XML Document
The following code snippet parses an XML document into an 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;
Parsing an XML String
The following code snippet parses an XML string into an XML DOM object:
txt="
txt=txt+"
txt=txt+"
txt=txt+"
txt=txt+"";
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.
Cross-domain access
For security reasons, modern browsers do not allow cross-domain access.
This means that the web page and the XML file it tries to load must be located on the same server.
XML DOM
In the next chapter, you will learn how to access an XML DOM object and retrieve data.