js加載xml(字符串或者文件)



1. 加載XML文件

使用ajax加載xml文件
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET", "data.xml", false);
xhr.send(null);
var xmlDoc = xhr.responseXML;
console.log(xmlDoc); 
IE加載xml文件
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.load("note.xml");
console.log(xmlDoc); 
Firefox加載xml文件
var xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = "false";
xmlDoc.load("note.xml");
console.log(xmlDoc);

2. 加載XML字符串

function LoadXmlText() {

            //拼接XML字符串
            var txt = '';
            txt = txt + "<note>";
            txt = txt + "<to>George</to>";
            txt = txt + "<from>John</from>";
            txt = txt + "<heading>Reminder</heading>";
            txt = txt + "<body>Don't forget the meeting!</body>";
            txt = txt + "</note>";

            
            if (window.DOMParser) {
                //非IE瀏覽器
                xmlDoc = (new DOMParser()).parseFromString(txt, "text/xml");
            } else {
                //IE瀏覽器
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");         
                // 或者:xmlDoc = new ActiveXObject("MSXML2.DOMDocument");      

                xmlDoc.async = "false";        //不啓用異步,保證加載文件成功之前不會進行下面操作
                xmlDoc.loadXML(txt);
            }

            console.log(xmlDoc);
        }

老是重複的找,這裏記錄下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章