XML 應用程式


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


XML 文檔實例

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


在 HTML div 元素中顯示第一個 CD

下麵的實例從第一個 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--;
displayCD();
}
}



當點擊 CD 時顯示專輯資訊

最後的實例展示如何在用戶點擊某個 CD 專案時顯示專輯資訊:

如需瞭解更多關於使用 JavaScript 和 XML DOM 的資訊,請訪問我們的 XML DOM 教學