From http://www.w3schools.com (Copyright Refsnes Data)
| « Previous | Next Chapter » |
This chapter demonstrates a small XML application built with HTML and JavaScript.
Look at the following XML document ("cd_catalog.xml"), that represents a CD catalog:
| <?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> . . . |
View the full "cd_catalog.xml" file.
To load the XML document (cd_catalog.xml), we use the same code as we used in the XML Parser chapter:
| if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // Internet Explorer 5/6 { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","cd_catalog.xml",false); xhttp.send(""); xmlDoc=xhttp.responseXML; |
After the execution of this code, xmlDoc is an XML DOM object, accessible by JavaScript.
The following code displays an HTML table filled with data from the XML DOM object:
Example
Try it yourself » |
For each CD element in the XML document, a table row is created. Each table row contains two table data with ARTIST and TITLE from the current CD element.
XML data can be copied into any HTML element that can display text.
The code below is part of the <head> section of the HTML file. It gets the XML data from the first <CD> element and displays it in the HTML element with the id="show":
Example
The body of the HTML document contains an onload event attribute that calls the display() function when the page is loaded. It also contains a <div id='show'> element to receive the XML data.
Try it yourself » |
In the example above, you will only see data from the first CD element in the XML document. To navigate to the next CD element, you have to add some more code.
To add navigation to the example above, create two functions called next() and previous():
Example
The next() function displays the next CD, unless you are on the last CD element. The next() and previous() functions are called by clicking next/previous buttons:
Try it yourself » |
With a little creativity you can create a full application.
If you use what you have learned on this page, and a little imagination, you can easily develop this into a full application.
Try it yourself: See how you can add a little fancy to this application.
For more information about using JavaScript and the XML DOM, visit our XML DOM tutorial.
| « Previous | Next Chapter » |
From http://www.w3schools.com (Copyright Refsnes Data)