近日一朋友让我给他网站改一下bug,并新增了.mobileconfig解析功能,博主百度了一下没有发现类似的解析方法。所以博主写了一个比较水的方法来解析。

function XmlToObject(xml){
    let xObj=(new DOMParser()).parseFromString(xml,'text/xml');
    let dict=xObj.querySelector('plist');
    function GetData(dict){
        //开始解析
        let retObj={};
        try{
            let nodeName=dict.nodeName;
            if(/dict/.test(nodeName)){
                //Object
                retObj={};
                if(dict.children){
                    for (let i=0;i<dict.children.length;i++){
                        let keyName=dict.children[i].nodeName;
                        if(/key/.test(keyName)){
                            keyName=dict.children[i].textContent;
                            let node=dict.children[++i];
                            let value=node.textContent;
                            if(/true|false/.test(node.nodeName)){
                                value= eval(node.nodeName);
                            }else if(/integer/.test(node.nodeName)){
                                value= eval(value);
                            }else if(/array/.test(node.nodeName)){
                                //数组-嵌套循环
                                value=[];
                                for (let j=0;j<node.children.length;j++){
                                    value.push(GetData(node.children[j]));
                                }
                            }else if(/dict/.test(node.nodeName)){
                                //Object
                                value=GetData(node.nodeName);
                            }else{
                                value=value.replace(/\s+/g, "");
                            }
                            retObj[keyName]=value;
                        }else if(/dict/.test(keyName)){
                            //Object
                            retObj=GetData(dict.children[i]);
                        }
                    }
                }
            }else if(/array|plist/.test(nodeName)){
                //array
                retObj=[];
                for (let j=0;j<dict.children.length;j++){
                    retObj.push(GetData(dict.children[j]));
                }
            }
        }catch (e) {
            debugger
        }
        return retObj;
    }
    return GetData(dict);
}

标签: js

添加新评论