XML application
This chapter demonstrates some small XML applications built on XML, HTML, XML DOM and JavaScript.
XML Document Example
In this application, we will use the "cd_catalog.xml" file.
Display the first CD in an HTML div element
The following example gets the XML data from the first CD element, and then displays it in the HTML element with id="showCD" Display Data. The displayCD() function is called when the page loads:
Instance
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; }
Run Instance»
Click "Run Instance" Button to view the online instance
In order to add navigation (function) to the above instance, you need to create next() and previous() two functions:
Instance
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(); } }
Running Example»
Click the "Run Instance" button to view the online instance
Display album information when the CD is clicked
The final example shows how to display album information when the user clicks on a CD item:
Try it out.
To learn more about using JavaScript and the XML DOM, visit our XML DOM tutorial.