XML application


May 27, 2021 19:00 XML


Table of contents


XML application


This chapter demonstrates some small XML applications built on XML, HTML, XML DOM, and JavaScript.


XML document instance

In this application, we will use the "cd_catalog.xml" file.


The first CD is displayed in the HTML div element

The following example gets XML data from the first CD element, and then displays the data in the HTML element of the id"showCD". The displayCD() function is called when the page loads:

x=xmlDoc.getElementsByTagName("CD");
i=0;

function displayCD()
{
artist=(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
title=(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
year=(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue);
txt="Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year;
document.getElementById("showCD").innerHTML=txt;
}

Try it out . . .


Add a navigation script

In order to add navigation (functionality) to the instance above, you need to create two functions, next() and previous():

function next()
{ // display the next CD, unless you are on the last CD
if (i<x.length-1)
{
i++;
displayCD();
}
}

function previous()
{ // displays the previous CD, unless you are on the first CD
if (i>0)
{
i--;
displayCD();
}
}

Try it out . . .


Show album information when you tap the CD

The last instance shows how album information is displayed when a user clicks on a CD item:

Try .

To learn more about using JavaScript and XML DOM, visit our XML DOM tutorial.