Using Jquery I am parsing an XML file and adding an attribute to every element nodes.
After manipulated xml is returned to the caller I can’t get the added attibute, it says it is undefined.
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);
Attribute I am adding is JSON data in format
{"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;
}
I am not getting the stats attribute in the returned xmlDoc that i have added. It is saying undefined. Let me know what I am doing wrong here.
Thank you very much for your time.
Fixed the stats property problem.
Accoring to JQuery
.attr() should not be used on plain objects, arrays, the window,
You have to use .data(‘stats’, {}) to set object base data like json. I have added the code in stats property is showing properly now