xml 看起来像:-
<childrens>
<child_1 entity_id="1" value="Root Catalog" parent_id="0">
<child_2 entity_id="2" value="Navigate" parent_id="1">
<child_4 entity_id="4" value="Activities" parent_id="2">
<child_10066 entity_id="10066" value="Physical1" parent_id="4">
<child_10067 entity_id="10067" value="Cricket" parent_id="10066">
<child_10068 entity_id="10068" value="One Day" parent_id="10067"/>
</child_10067>
</child_10066>
<child_10069 entity_id="10069" value="Test2" parent_id="4"/>
<child_10070 entity_id="10070" value="Test3" parent_id="4"/>
<child_10071 entity_id="10071" value="Test4" parent_id="4"/>
<child_10072 entity_id="10072" value="Test5" parent_id="4"/>
<child_5 entity_id="5" value="Physical" parent_id="4"/>
</child_4>
<child_4331 entity_id="4331" value="Region" parent_id="2">
<child_4332 entity_id="4332" value="Asia" parent_id="4331">
<child_4333 entity_id="4333" value="Afghanistan" parent_id="4332">
<child_4334 entity_id="4334" value="Balkh" parent_id="4333">
<child_4335 entity_id="4335" value="Mazar-e-Sharif" parent_id="4334"/>
</child_4334>
<child_4336 entity_id="4336" value="Herat" parent_id="4333">
<child_4337 entity_id="4337" value="Herat" parent_id="4336"/>
</child_4336>
</child_4333>
</child_4332>
</child_4331>
</child_2>
</child_1>
</childrens>
在上面的 xml 文件中,我尝试在不同的变量中获取所有活动和区域。
这个试过了。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var result_region='';
var node_region;
var comma_region='';
var activity;
var result_activity='';
var node_activity;
var comma_activity='';
var region;
$(document).ready(function(){
$.ajax({
url: 'final.xml',
type:"get",
async: false,
success: function(xml) {
var xPath_region = '//child_4/*[@value]' + '/@value';
var xPath_activity = '//child_4331/*[@value]' + '/@value';
var iterator = xml.evaluate(xPath_region, xml.documentElement, null,
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
var thisNode = iterator.iterateNext();
while (thisNode) {
node_region = thisNode.textContent;
thisNode = iterator.iterateNext();
if(result_region.indexOf(node_region) == -1){
result_region += comma_region+node_region;
comma_region=',';
}
}
var iterator = xml.evaluate(xPath_activity, xml.documentElement, null,
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
var thisNode = iterator.iterateNext();
while (thisNode) {
node_activity = thisNode.textContent;
thisNode = iterator.iterateNext();
if(result_activity.indexOf(node_activity) == -1){
result_activity += comma_activity+node_activity;
comma_activity=',';
}
}
activity = result_region;
region = result_activity;
alert(activity);
alert(region);
},
});
});
</script>
以上代码返回:-
var activity = "Physical1,Test2,Test3,Test4,Test5";
var region = "Asia";
它唯一返回第一级节点 b'coz 我在 xpath 上尝试找到Child_4
我想要所有子节点和子节点。
喜欢:-
var activity = "Physical1,Cricket,One Day,Test2,Test3,Test4,Test5";
var region = "Asia,Afghanistan,Balkh,Mazar-e-Sharif,Herat,Herat";
我怎样才能获得所有孩子和孩子的子孩子价值。
谢谢。