如何使用JQuery正确返回已操作的XML文档
我使用Jquery解析XML文件,并向每个元素节点添加属性。 在处理过的xml返回给调用方后,我无法获得添加的attibute,它表示它未定义如何使用JQuery正确返回已操作的XML文档,jquery,attributes,xml-parsing,Jquery,Attributes,Xml Parsing,我使用Jquery解析XML文件,并向每个元素节点添加属性。 在处理过的xml返回给调用方后,我无法获得添加的attibute,它表示它未定义 function loadTreeML(dname){ var xmlDoc; $.ajaxSetup({ async: false }); $.ajax({ type: "GET", url: dname,
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);
我添加的属性是JSON格式的数据
{"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中获得stats属性。它说的是未定义的。让我知道我做错了什么。
非常感谢您的时间。您的遍历代码试图将javascript对象child_stats设置为stats属性的值。在这种类型的attr函数中,只有字符串是合法的值类型,jQuery非常明智地拒绝设置非法值,而不是(比如)将对象强制为json字符串。这就是为什么属性随后显示为未定义
如果改为调用$tree.attrchild_stats,您将看到XML节点中填充的属性数量与child_stats对象中的属性数量相同。无论如何,这可能是您真正希望发生的事情。修复了stats属性问题。 根据JQuery .attr不应用于普通对象、数组、窗口、 您必须使用.data'stats',{}来设置对象基础数据,如json。我已经添加了stats属性中的代码,现在可以正常显示了
$(tree).data('stats',child_stats);
你能发布遍历函数代码吗?