首页 » JavaScript » DOM2级兼容旧版IE创建兼容的loadXML()和.xml方法

最后更新于 2018年10月24日

前言:

由于DOM2不支持load()从外部加载xml文件,所以只能做loadXML()的兼容方法,有点可惜!

创建兼容的loadXML():

function createXMLDom(value){
    var xmlDom = null;
    if(typeof window.DOMParser != 'undefined') {
        xmlDom = (new DOMParser()).parseFromString(value,'text/xml');
        //alert((new XMLSerializer()).serializeToString(xmlDom)); //用来查看错误的xml里的信息
        var error = xmlDom.getElementsByTagName('parsererror');   //只有错误的xml里面才有parsererror标签;
        if(error.length > 0){
            throw new Error('错误信息:'+ error[0].textContent);
        }
    }else if(typeof window.ActiveXObject != 'undefined'){
        var xmlvie = ['MSXML2.DOMDocument.6.0','MSXML2.DOMDocument.3.0','MSXML2.DOMDocument'];
        for(var i = 0;i < xmlvie.length;i++){
            try {
                xmlDom = new ActiveXObject(xmlvie[i]);
            } catch(e) {
                //跳过
            }
            xmlDom.loadXML(value);            
        }
        if(xmlDom.parseError != 0) {
            throw new Error('错误行号:'+ xmlDom.parseError.line +
                            '\n错误代号:' + xmlDom.parseError.errorCode +
                            '\n错误解释:' + xmlDom.parseError.reason);
        }
    }else {
        throw new Error('当前浏览器或者系统不支持XML DOM');
    }
    
    return xmlDom;
}

创建兼容的.xml方法:

function serialize(xmlDom){
    var xml = '';
    if(typeof window.XMLSerializer != 'undefined') {
        xml = (new XMLSerializer()).serializeToString(xmlDom);
    }else if(typeof xmlDom.xml != 'undefined') {
        xml = xmlDom.xml;
    }
    return xml;
}

运行:

var xmlstr = '<root><user>lee</user></root>';
var xmlDom = createXMLDom(xmlstr);
var xml = serialize(xmlDom);
alert(xml);
  • weixiao kaixin tushetou jingkong deyi fanu liezui liuhan daku ganga bishi nanguo lihai qian yiwen numu tu yi haixiu se fadai minyan hehe henkaixin huaji biyiyan kuanghan maimeng shui xiaku penqi zhangzui pen aini ye niu laji ok chigua renshi kongbu shuai xiaoxiese touxiao huaixiao jingnu chihuai kaisang xiaoku koubi zhuangbi lianhong kanbujian shafa zhijing xiangjiao dabian yaowan redjing lazhu rizhi duocang chixigua hejiu xixi xiaopen goukun xiaobuchu shenme wusuowei guancha lajing chouyan xiaochi bie zhadanzui zhadanxiao