前言:

由于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);

分类: JavaScript 标签: .xmlActiveXObjectloadXMLparseFromStringDOMParserXMLSerializerserializeToString

评论

暂无评论数据

暂无评论数据

目录