天天看點

XML 應用程式

本章示範一些基于 XML, HTML, XML DOM 和 JavaScript 建構的小型 XML 應用程式。

在本應用程式中,我們将使用 "cd_catalog.xml" 檔案。

下面的執行個體從第一個 CD 元素中擷取 XML 資料,然後在 id="showCD" 的 HTML 元素中顯示資料。displayCD() 函數在頁面加載時調用:

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;

}

為了向上面的執行個體添加導航(功能),需要建立 next() 和 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--;

最後的執行個體展示如何在使用者點選某個 CD 項目時顯示專輯資訊:

嘗試一下。

如需了解更多關于使用 JavaScript 和 XML DOM 的資訊,請通路我們的 XML DOM 教程。