XML Applications
This chapter demonstrates some small XML applications built with XML, HTML, XML DOM, and JavaScript.
XML Document Example
In this application, we will use"cd_catalog.xml"file.
Display the first CD in an HTML div element
The example below gets XML data from the first CD element and displays the data in the HTML element with id="showCD". The displayCD() function is called when the page loads:
Example
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;
}
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 Yourself »
Add Navigation Script
To add navigation (functionality) to the example above, you need to create two functions: next() and previous():
Example
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();
}
}
{ // 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 Yourself »
Display album information when clicking a CD
The final example shows how to display album information when the user clicks a CD item:
For more information about using JavaScript and the XML DOM, please visit ourXML DOM Tutorial。
Other Extensions