HTML5 表單元件:server端,開啟xml檔,並直接轉成 xml物件 (下載person.xml)
(要用chrome才能查詢到xml資料)



 


1.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);
}

1.重要觀念:
在server端是用loadxml的方式讀進的是整個xml物件(不是純文字檔),好處是可以直接由xmlDoc物件抓到所需的數據,缺點是若要輸出全部xml內容在螢幕上,則必須先將xml物件轉成字串

2.步驟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","product.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

3.步驟2:由xmlDoc物件,抓出所需的資料

第1位學生的姓名:xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue
第1位學生的電話:xmlDoc.getElementsByTagName("tel")[0].childNodes[0].nodeValue
第2位學生的電話:xmlDoc.getElementsByTagName("tel")[1].childNodes[0].nodeValue

讀取的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);
}

4.步驟3:若需輸出全部xml內容在螢幕上,則要先將xml物件轉成字串

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

5.xml物件,與xml字串互相轉換的公式

(1).將字串轉換成 XML 物件

function convert_string_to_xml(strXML)
{
if (window.ActiveXObject) {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(strXML);
return xmlDoc;
} else {
parser=new DOMParser();
xmlDoc=parser.parseFromString(strXML,"text/xml");
return xmlDoc;
}
}

(2).將 XML 物件轉換成字串

function convert_xml_to_string(xmlObject)
{
if (window.ActiveXObject) { // for IE
return xmlObject.xml;
} else {
return (new XMLSerializer()).serializeToString(xmlObject);
}
}