2012-02-07 87 views
0

我正在学习jQuery和我碰到的一个问题,我似乎无法避开组...解析XML的使用jQuery

我有一个看起来像这样的XML文档:

<?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> 

而现在我使用这个:

$(document).ready(function(){ 
    $.ajax({ 
     type: "GET", 
     url: "xml/food.xml", 
     dataType: "xml", 
     success: foodXML 
    }); // close ajax 
}); 

function foodXML(xml) { 

    $(xml).find('item').each(function() { 
     $('#foodItem').append('<li>' + $(this).attr("name") + '</li>'); 
    }); 

} 

得到这个:

Apple 
Onion 
Banana 
Pineapple 
Carrot 
Orange 

但我想要得到它做的是列出他们这样的:

A 
Apple 
Onion 
B 
Banana 
Pineapple 
C 
Carrot 
Orange 

任何帮助吗?我似乎无法理解这一点。

回答

0

看看这些组,然后遍历它的孩子。例如,

function foodXML(xml) { 

    var $fooditem = $('#foodItem'); 

    $('group', xml).each(function() { 
      var $items = $('item', this); 
      if($items.length){ 
       $fooditem.append('<li>' + $items.first().attr("name").charAt(0) + '</li>'); 
       $items.each(function(){ 
        $fooditem.append('<li>' + $(this).attr("name") + '</li>'); 
       }); 
      } 
    }); 

} 
+0

非常感谢!我会看看我是否可以得到这个工作... – neirpycc 2012-02-07 15:09:14

0

您可以使用$ .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>'); 
    }); 
    }) 

}