使用JQuery在组中解析XML
我正在学习JQuery,遇到了一个似乎无法解决的问题 我有一个如下所示的XML文档:使用JQuery在组中解析XML,jquery,xml,ajax,parsing,Jquery,Xml,Ajax,Parsing,我正在学习JQuery,遇到了一个似乎无法解决的问题 我有一个如下所示的XML文档: <?xml version="1.0" encoding="UTF-8"?> <food> <group name="Red"> <item name="Apple" type="Fruit"> <item name="Onion" type="Veggie"> </group> &l
<?xml version="1.0" encoding="UTF-8"?>
<food>
<group name="Red">
<item name="Apple" type="Fruit">
<item name="Onion" type="Veggie">
</group>
<group name="Yellow">
<item name="Banana" type="Fruit">
<item name="Pineapple" type="Fruit">
</group>
<group name="Orange">
<item name="Carrot" type="Veggie">
<item name="Orange" type="Fruit">
</group>
</food>
A
Apple
Onion
B
Banana
Pineapple
C
Carrot
Orange
但我想让它做的是这样列出它们:
<?xml version="1.0" encoding="UTF-8"?>
<food>
<group name="Red">
<item name="Apple" type="Fruit">
<item name="Onion" type="Veggie">
</group>
<group name="Yellow">
<item name="Banana" type="Fruit">
<item name="Pineapple" type="Fruit">
</group>
<group name="Orange">
<item name="Carrot" type="Veggie">
<item name="Orange" type="Fruit">
</group>
</food>
A
Apple
Onion
B
Banana
Pineapple
C
Carrot
Orange
有什么帮助吗?我似乎无法理解这一点。看看这些组,然后反复讨论它们的孩子们。比如说,
函数foodXML(xml){
变量$fooditem=$(“#fooditem”);
$('group',xml).each(函数(){
变量$items=$('item',this);
如果($items.length){
$fooditem.append(''+$items.first().attr(“name”).charAt(0)+' ');
$items.each(函数(){
$fooditem.append(''+$(this.attr(“name”)+' ');
});
}
});
}
您可以使用$.each函数遍历每个组,然后在每个组中查找项目
function foodXML(xml) {
$.each($(xml).find('group'), function(index, group){
$('#foodItem').append('<li>' + index + '</li>');
$(group).find('item').each(function() {
$('#foodItem').append('<li>' + $(this).attr("name") + '</li>');
});
})
}
函数foodXML(xml){
$.each($(xml).find('group'),函数(索引,组){
$(“#foodItem”).append(“