Wednesday, 21 April 2021

AJAX Web Application for Reading Data from XML

 cdcatalog.xml

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>RCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1982</YEAR>
  </CD>
</CATALOG>

readxml.html

<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc() 
{
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() 
{
if (this.readyState == 4 && this.status == 200) 
{
var xmlDoc = xhttp.responseXML;
var table="<table border='1'><tr><th>Title</th><th>Price</th><th>Year</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.lenght; i++) 
{
table += "<tr><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
"</td><td>"+
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue +
"</td></tr>"
}
table+="</table>";
document.getElementById("demo").innerHTML = table;
}
};
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
}
</script>
</head>
<body onload="loadDoc()">
<h1>Reading XML Data</h1>
<div id="demo"></div>
</body>
</html>