XML Parser using Javascript

Author: satz | Date: August 31, 2009

This article shows how to parse an XML file and write the data into an HTML page. Parsing XML using JavaScript is very much useful when there is no server side scripts to load dynamic data into an HTML file.

The skills required are, HTML,  Javascript and XML.

Follwing script needs to be defined in the header.

function loadXMLDoc(XMLname)
 {
 var xmlDoc;
 if (window.XMLHttpRequest)
 {
 xmlDoc=new window.XMLHttpRequest();
 xmlDoc.open("GET",XMLname,false);
 xmlDoc.send("");
 return xmlDoc.responseXML;
 }
 // IE 5 and IE 6
 else if (ActiveXObject("Microsoft.XMLDOM"))
 {
 xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 xmlDoc.async=false;
 xmlDoc.load(XMLname);
 return xmlDoc;
 }
 alert("Error loading document!");
 return null;
 }

The above function will parse the specified XML file (“XMLname” variable holds the xml file path. ) and create the XML document (xmlDoc ).

Put the following code in the body of the HTML page:

<script type="text/javascript">
 xmlDoc=loadXMLDoc("data.xml") // Path to the XML file;
 var M = xmlDoc.getElementsByTagName("article");
 for (i=0;i<M.length;i++){
 document.write("<div style='width:450px;'>")
 document.write("<h2>"+xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue+"</h2>");
 document.write("<p>"+xmlDoc.getElementsByTagName("description")[i].childNodes[0].nodeValue+"</p>");
 document.write("<p><a href='"+ xmlDoc.getElementsByTagName("url")[i].childNodes[0].nodeValue+"' target='_blank'>" +xmlDoc.getElementsByTagName("urltext")[i].childNodes[0].nodeValue+"</a></p>");
 document.write("</div>")
 }
 </script>

In this example, the xml file parsed is “data.xml” which is in the same directory of the HTML page.

The following script counts the number of instances of the specified tag (“article”).

var M = xmlDoc.getElementsByTagName(”article”);

Then basing on the number of instances, the following script creates the for loop for displaying the data:

for (i=0;i<M.length;i++){

The following script would return the value of the “title” tags based on the (“i”) value in the loop instance.

xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue

The first instance value will be “0″.

The structure of the XML in this article would be as follows:

<root>
 <article>
 <title></title>
 <description></description>
 <url></url>
 <urltext></urltext>
 </article>
 <article>
 <title></title>
 <description></description>
 <url></url>
 <urltext></urltext>
 </article>
 <article>
 <title></title>
 <description></description>
 <url></url>
 <urltext></urltext>
 </article>
 </root>

NOTE: When there is a possibility of using a server side script to parse the XML file, preference should be given for server side script, because, the server side scripts can parse the XML file more efficiently.

Click here to download the sample files.