Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XML parser


May 27, 2021 XML


Table of contents


XML Parser

XML parsers are used to check the appropriate format for XML documents and can also validate XML documents.

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.


Resolve the XML document

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;


Resolve the XML string

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.


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 is trying to load must be on the same server.


XML DOM

In the next section, you'll learn how to access XML DOM objects and get your data back.