XML DOM 加載函數(shù)


加載 XML 文檔中的代碼可以存儲在一個函數(shù)中。


loadXMLDoc() 函數(shù)

為了使前一頁中的代碼易于維護(hù)(檢查舊的瀏覽器),它應(yīng)該寫成一個函數(shù):

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;
}

上面的函數(shù)可以存儲在 HTML 頁面的 <head> 部分,并從頁面中的腳本調(diào)用。

lamp.gif上面描述的函數(shù),用于本教程中所有 XML 文檔實(shí)例!


loadXMLDoc() 的外部 JavaScript

為了使上述代碼更容易維護(hù),以確保在所有頁面中使用相同的代碼,我們把函數(shù)存儲在一個外部文件中。

文件名為 "loadxmldoc.js",且在 HTML 頁面中的 head 部分被加載。然后,頁面中的腳本調(diào)用 loadXMLDoc() 函數(shù)。

下面的實(shí)例使用 loadXMLDoc() 函數(shù)加載 books.xml:

實(shí)例

<!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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例

如何從 XML 文件中獲得數(shù)據(jù),將在下一章中講解。


loadXMLString() 函數(shù)

為了使前一頁中的代碼易于維護(hù)(檢查舊的瀏覽器),它應(yīng)該寫成一個函數(shù):

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;
}

上面的函數(shù)可以存儲在 HTML 頁面的 <head> 部分,并從頁面中的腳本調(diào)用。

lamp.gif上面描述的函數(shù),用于本教程中所有 XML 字符串實(shí)例!


loadXMLString() 的外部 JavaScript

我們已經(jīng)把 loadXMLString() 函數(shù)存儲在名為 "loadxmlstring.js" 文件中。

實(shí)例

<!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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例