Xml Parser
# XML Parser
* * *
All modern browsers have a built-in XML parser.
The 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+"Everyday Italian ";
txt=txt+"Giada De Laurentiis";
txt=txt+"2005";
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 XML strings, while other browsers use the DOMParser object.
* * *
## Cross-Domain Access
For security reasons, modern browsers do not allow cross-domain access.
This means that both the web page and the XML file it tries to load must reside on the same server.
* * *
## XML DOM
In the next chapter, you will learn how to access the XML DOM object and retrieve data.
YouTip