2012-02-07 169 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>'); 
    }); 
    }) 

}