/**
* 加载 xml 文件
* @param {String} url 文件 url 地址
*/
function loadHTTP(url) {
    let xhttp;

    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhttp.open("GET", url, false);
    xhttp.send();

    return xhttp.responseXML;
}

/**
* xml 字符串转换 xml 对象
* @param {String} content xml 字符串
*/
function loadXML(content) {
    var result = {};

    // document.all 判断浏览器是否是IE 
    if (document.all) {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(content);
        result = xmlDom;
    } else {
        result = new DOMParser().parseFromString(content, "text/xml");
    }

    return result;
}

const XML_LOAD = {

    loadHTTP: loadHTTP,
    loadXML: loadXML,

    /**
     * 获取 xml 文档的编码
     * @param {String} xmlFileText xml 文件文本
     */
    getXMLEncoding: function (xmlFileText) {
        let result = "";
        if (xmlFileText) {
            let xmlDoc = loadXML(xmlFileText);
            result = xmlDoc.xmlEncoding;
        }

        console.log('xml encoding:');
        console.log(result);

        return result;
    },

    /**
     * xml 对象转字符串
     * @param {Object} xmlObject xml dom 对象
     */
    convertXML2String: function (xmlObject) {
        // for IE
        if (window.ActiveXObject) {
            return xmlObject.xml;
        }
        // for other browsers
        else {
            return (new XMLSerializer()).serializeToString(xmlObject);
        }
    }
}

export default XML_LOAD