讀取server端xml資料, 以上一筆,下一筆顯示資料(下載person.xml)
(要用chrome才能查詢到xml資料)



(1).讀取server端xml資料:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","xml/person.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

(2).讀取的XML(xmlDoc)如何抓到所有學生student的結構資料
man=xmlDoc.getElementsByTagName("student");
*第3位學生的電話:man[2].getElementsByTagName("tel")[0].childNodes[0].nodeValue
*印出所有學生student的姓名:

for (i=0;i<man.length;i++)
{
document.write(man[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
}

(3).如何以上一筆,下一筆顯示資料

步驟1:建立1個changedata(i)函數
function changedata(i) {
str ="學號: ";
str += man[i].getElementsByTagName("id_no")[0].childNodes[0].nodeValue;document.getElementById("id01").innerHTML = str }

步驟2:建立next()函數來控制到下一筆
function next() {
i++;
if(i>man.length){i=0;}
changedata(i); }

5.xml字串與xmlDoc節點變數彼此轉換的公式

//將xml字串轉成xmlDoc節點變數:
xmlDoc =parser.parseFromString(txt,"text/xml");

//將字串轉成xmlDoc節點變數
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);
}

//將xml物件轉成xml字串:
xmlString
=(new XMLSerializer()).serializeToString(xmlDoc)

//將xml物件轉成string文字
if (window.ActiveXObject) { // for IE 瀏覽器
txt01.value = xmlDoc.xml;
} else { //chrome, firefox,Opera各種瀏覽器
txt01.value = (new XMLSerializer()).serializeToString(xmlDoc);
}

 

(5).person.xml結構
var stu = new Array(); //一維陣列 物件
<?xml version="1.0" standalone="yes"?>
<person>
<student>
<id_no>9096036</id_no>
<name>蔡文龍</name>
<tel>04-32345671</tel>
<mail>lung67@giga.net.tw</mail>
</student>
<student>
<id_no>9096001</id_no>
<name>許百宏</name>
<tel>04-12345671</tel>
<mail>em@ms37.hient.net</mail>
</student>
<student>
<id_no>9096002</id_no>
<name>林宜美</name>
<tel>04-78955671</tel>
<mail>em@ms37.yam.net</mail>
</student>
<student>
<id_no>9096003</id_no>
<name>賴玲英</name>
<tel>049-6345671</tel>
<mail>pc@ms56.hient.net</mail>
</student>
<student>
<id_no>9096004</id_no>
<name>丁勝勇</name>
<tel>02-12344471</tel>
<mail>em@ms37.hient.seed.tw</mail>
</student>
<student>
<id_no>9096005</id_no>
<name>劉曉珍</name>
<tel>049-1345671</tel>
<mail>yy@ms45.hient.net</mail>
</student>
<student>
<id_no>9096006</id_no>
<name>李逢源</name>
<tel>06-11235671</tel>
<mail>et@ms37.yam.net</mail>
</student>
<student>
<id_no>9096007</id_no>
<name>卓水信</name>
<tel>02-17896671</tel>
<mail>em@ms37.pchome.net</mail>
</student>
<student>
<id_no>9096008</id_no>
<name>謝沂臻</name>
<tel>049-1234571</tel>
<mail>em@ms56.pchome.net</mail>
</student>
<student>
<id_no>9096009</id_no>
<name>徐志宏</name>
<tel>04-15465671</tel>
<mail>pp@ms69.hient.net</mail>
</student>
</person>