查找使用jQuery XML后裔 [英] Find descendant from XML using jQuery
问题描述
我有一个XML文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<childrens>
<child id="1" value="Root Catalog" parent_id="0">
<child id="2" value="Apparel" parent_id="1">
<child id="3" value="Accessories" parent_id="2">
<child id="4" value="Handbags" parent_id="3">
<child id="5" value="Jewelry" parent_id="4"/>
<child id="6" value="test1" parent_id="4"/>
<child id="7" value="test2" parent_id="4"/>
<child id="15" value="test3" parent_id="4"/>
</child>
</child>
</child>
<child id="8" value="test_A" parent_id="1">
<child id="9" value="test_B" parent_id="8">
<child id="10" value="test_C" parent_id="9">
<child id="11" value="test_D" parent_id="10"/>
</child>
</child>
</child>
.
.
.
.
.
.
<child id="1111" value="test" parent_id="1">
<child id="1112" value="test1" parent_id="1111">
<child id="1113" value="test12" parent_id="1112">
<child id="1114" value="test123" parent_id="1113"/>
<child id="1115" value="test1234" parent_id="1114"/>
</child>
</child>
<child id="1116" value="test12345" parent_id="1111"/>
</child>
</child>
</childrens>
我想找到所有的的后裔的(所有的孩子,直到叶节点)的特定节点。例如,下面测试
的后裔 test1的,TEST12,test123,test1234和放大器; test12345
I want to find all the descendants (with all children up until leaf node) of a particular node. For example, here test
's descendants are test1,test12,test123,test1234 & test12345
如果我发现后代为测试1
,那么结果将是 TEST12,test123,test1234
。
If I find descendants for test1
, then result will be test12,test123,test1234
.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('child[value="test"]').children().each(function(){
var i = $(this).attr('value');
alert(i);
});
}
});
});
使用jQuery的。儿童()
给我的只有该节点的直接子。它不会给其孙子。例如,测试
它会提醒仅测试1和放大器; test12345
。
The use of jQuery .children()
gives me only that node's immediate child. It will not give its grandchildren. For example, for test
it will alert only test1 & test12345
.
推荐答案
您可以通过执行pre序遍历实现它。它是一种递归函数巫婆将处理节点,你想要的顺序。请参阅<一href="http://stackoverflow.com/questions/2082550/how-to-write-a-simple-$p$porder-dom-tree-traversal-algorithm-in-jquery">How在jQuery的编写一个简单的preorder DOM树遍历算法?
You can achieve it by doing a pre-order traversal. Its a recursive function witch will process the nodes the order you want. See How to write a simple preorder DOM tree traversal algorithm in jQuery?
考虑@ K-总理的回答,你的榜样是:
Considering @k-prime answer, your example will be:
$(xml).find('child[value="test"]').children().each (function processNodes()
{
alert($(this).attr('value'));
if (this.nodeType != 3)
$(this).children().each(processNodes);
});
作为分隔功能:
function recursiveDescendantsValues(node, arr) {
node.children().each(function () {
arr.push($(this).attr('value'));
if ($(this).nodeType != 3) {
recursiveDescendantsValues($(this), arr);
}
});
}
jQuery.fn.descendantsValues = function() {
var arr = []
recursiveDescendantsValues($(this), arr);
return arr;
};
希望它能帮助!
这篇关于查找使用jQuery XML后裔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!