使用Jquery我解析XML文件並向每個元素節點添加屬性。 操縱xml返回給調用者後,我無法獲得添加的屬性,它說它是未定義的。如何正確返回使用JQuery操作的XML文檔
function loadTreeML(dname){
var xmlDoc;
$.ajaxSetup({
async: false
});
$.ajax({
type: "GET",
url: dname,
dataType: "xml",
success: function(xml) {
var firstBranch =$(xml).find('branch').get(0);
if (typeof firstBranch != "undefined")
traverse(firstBranch, {"children":1, "siblings":0, "level":-1, "depth":0, "weight":1, "leaves":0, "strahlernum":0});
xmlDoc = xml;
}
});
//should return manipulated xml
return xmlDoc;
}
//updating attribute in traverse function
$(tree).attr('stats',child_stats);
屬性我加入是格式
{"children":1, "siblings":0, "level":-1, "depth":0, "weight":1, "leaves":0, "strahlernum":0}
function traverse(tree, parent_stats)
{
var child_stats = {"children":0, "siblings":0, "level":0, "depth":0, "weight":1, "leaves":0, "strahlernum":0};
//Counting the child node
$(tree).children().each(function(){
var kid = $(this);
if((kid.get(0).tagName.toLowerCase()== "branch")|| (kid.get(0).tagName.toLowerCase() == "leaf"))
child_stats.children++;
});
//alert(child_stats.children);
//Sibling
child_stats.siblings = parent_stats.children - 1;
//alert(child_stats.siblings);
//Level
child_stats.level = parent_stats.level + 1;
//DFS
if($(tree).get(0).tagName.toLowerCase() == "branch")
{
var offset = -1;
$(tree).children().each(function(){
var kid = $(this);
if((kid.get(0).tagName.toLowerCase()== "branch")|| (kid.get(0).tagName.toLowerCase() == "leaf")){
var temp_stats = traverse(kid,child_stats);
//count leaves
child_stats.leaves += temp_stats.leaves;
//determine depth
if(child_stats.depth < temp_stats.depth+1) child_stats.depth = temp_stats.depth+1;
//compute weight
child_stats.weight += temp_stats.weight;
//computer strahler
if ((child_stats.strahlernum != temp_stats.strahlernum)&&(child_stats.strahlernum != 0)) offset = -2;
child_stats.strahlernum = Math.max(child_stats.strahlernum, temp_stats.strahlernum);
}
child_stats.strahlernum += child_stats.children + offset;
});
}
else { //leaf
child_stats.leaves = child_stats.strahlernum = 1;
}
//Adding stats attribute write to XML
$(tree).attr('stats',child_stats);
return child_stats;
}
我沒有得到的統計數據中,我已經添加了返回xmlDoc中屬性JSON數據。這是說未定義的。讓我知道我在這裏做錯了什麼。 非常感謝您的時間。
你可以發佈'遍歷'功能代碼嗎? – wdm
添加了遍歷功能 – ZabedAkbar