原生javascript實現解析XML文檔與字符串
更新時間:2016年03月01日 08:56:49 投稿:hebedich
這篇文章主要介紹了javascript解析XML文檔和XML字符串的方法和具體的代碼解析,有需要的小伙伴可以參考下。
之前寫過一篇 《使用jquery解析XML的方法》鏈接是http://www.fzitv.net/article/54842.htm,上篇文章詳細解釋了jQuery 與字符串互相轉換的方法 ,這里著重論述javascript操作xml。
總代碼如下:
var XMLHttp = null;
if (window.XMLHttpRequest) { //現代瀏覽器
XMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6
}
if (XMLHttp !== null) {
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState === 4) {
if (XMLHttp.status === 200 || XMLHttp.status === 304) {
// var XMLDom = XMLHttp.responseXML; //解析XML文檔
var XMLDoc = XMLHttp.responseText; //解析XML字符串
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
//異步代碼寫這里
console.log(XMLDom);
console.log("world"); //后出現world
}
}
};
XMLHttp.open("get", "test1.xml", true);
XMLHttp.send();
//非異步代碼寫這里
console.log("hello"); //先出現hello
}
第一步,創(chuàng)建XMLHTTPREQUEST:
var XMLHttp = null;
if (window.XMLHttpRequest) { //現代瀏覽器
XMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6
}
第二步,檢測ONREADYSTATECHANGE(非異步不需要):
if (XMLHttp !== null) {
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState === 4) {
if (XMLHttp.status === 200 || XMLHttp.status === 304) {
//異步代碼寫這里
}
}
};
XMLHttp.open("get", "test1.xml", true);
XMLHttp.send();
//非異步代碼寫這里
}
第三步,解析XML文檔或字符串(異步):
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState === 4) {
if (XMLHttp.status === 200 || XMLHttp.status === 304) {
// var XMLDom = XMLHttp.responseXML; //解析XML文檔
var XMLDoc = XMLHttp.responseText; //解析XML字符串
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
//異步代碼寫這里
console.log(XMLDom);
}
}
};
第四步,解析XML文檔或字符串(非異步):
if (XMLHttp !== null) {
// XMLHttp.onreadystatechange = function() {
// if (XMLHttp.readyState === 4) {
// if (XMLHttp.status === 200 || XMLHttp.status === 304) {}
// }
// };
XMLHttp.open("get", "test1.xml", false);
XMLHttp.send();
//非異步代碼寫這里
// var XMLDom = XMLHttp.responseXML; //解析XML文檔
var XMLDoc = XMLHttp.responseText; //解析XML字符串
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
//異步代碼寫這里
console.log(XMLDom);
}
相關文章
BootStrap 輪播插件(carousel)支持左右手勢滑動的方法(三種)
這篇文章主要介紹了BootStrap 輪播插件(carousel)支持左右手勢滑動的方法(三種)的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-07-07
Sample script that displays all of the users in a given SQL
Sample script that displays all of the users in a given SQL Server DB...2007-06-06

