XML DOM 教學課程登入
XML DOM 教學課程
作者:php.cn  更新時間:2022-04-13 15:27:56

DOM 載入函數


XML DOM 載入函數


載入 XML 文件中的程式碼可以儲存在一個函數中。


loadXMLDoc() 函數

為了讓前一頁中的程式碼易於維護(檢查舊的瀏覽器),它應該寫成一個函數:

#function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
#{##xhttp =new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
上面的函數可以儲存在HTML 頁面的<head> 部分,並從頁面中的腳本呼叫。

上面描述的函數,用於本教學課程中所有 XML 文件實例! lamp.gif


loadXMLDoc() 的外部JavaScript

為了讓上述程式碼更容易維護,以確保在所有頁面中使用相同的程式碼,我們將函數儲存在一個外部文件中。

檔案名稱為 "loadxmldoc.js",且在 HTML 頁面中的 head 部分被載入。然後,頁面中的腳本呼叫 loadXMLDoc() 函數。

下面的實例使用loadXMLDoc() 函數載入books.xml:

#實例

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br>");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

執行實例»點擊"運行實例" 按鈕查看線上實例

如何從XML 檔案中獲得數據,將在下一章中講解。


loadXMLString() 函數

為了讓前一頁中的程式碼易於維護(檢查舊的瀏覽器),它應該寫成一個函數:

function loadXMLString(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml" );
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt );
}
return xmlDoc;
}
上面的函數可以儲存在HTML 頁面的<head> 部分,並從頁面中的腳本呼叫。

上面描述的函數,用於本教學中所有 XML 字串實例! lamp.gif


loadXMLString() 的外部 JavaScript

我們已經把 loadXMLString() 函數儲存在名為 "loadxmlstring.js" 檔案中。

實例

<!DOCTYPE html>
<html>
<head>
<script src="loadxmlstring.js"></script>
</head>
<body>
<script>
text="<bookstore><book>";
text=text+"<title>Everyday Italian</title>";
text=text+"<author>Giada De Laurentiis</author>";
text=text+"<year>2005</year>";
text=text+"</book></bookstore>";

xmlDoc=loadXMLString(text);

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("<br>");
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue);
document.write("<br>");
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

運行實例»點擊"運行實例" 按鈕查看線上實例


#