遍历xml的两个方法

//前序
function parseSrc(dataSrc) {
    var childNodes:Array = dataSrc.childNodes;
    var result:Array = new Array();
    for (var i = 0; i<childNodes.length; i++) {
        var element:XML = childNodes;
        if (element.nodeType == 1 && element.hasChildNodes()) {
            parseSrc(element);
        }
        if (element.nodeType == 1) {
            result.push(element);
            trace(element.nodeName);
            element.removeNode();
        }else{
            trace(element+",value:"+element.nodeValue);
            element.removeNode();
        }
    }
}
//中序
function parseSrc(dataSrc:XML) {
    var childNodes:Array = dataSrc.childNodes;
    var result:Array = new Array();
    for (var i = 0; i<childNodes.length; i++) {
        var element:XML = childNodes;
        result.push(element.cloneNode(false));
        trace(element.cloneNode(false));
        if (element.hasChildNodes()) {
            parseSrc(element);
        }
    }
}
//非递归遍历,先访问叶,参考了数据结构的教材
function preParse(node) {
    var work:Array = new Array(); //工作栈
    var result:Array = new Array(); //结果栈
    for (; node.hasChildNodes() || work.length>0; ) {
        for (; node.hasChildNodes() && node.childNodes[0].nodeType == 1; ) {
            work.push(node);
            node = node.childNodes[0];
        }
        trace(node.nodeName);
        result.push(node);
        if (work.length>0) { 
            node.removeNode();
            //工作栈中有节点,继续遍历,在这里取出节点就是从根开始
            node = work.pop();
        }
    }
}

效率上,我认为递归的效率要高于迭代了。因为vm在栈段的优化要高于手工写的栈

你可能感兴趣的:(xml)