0

我有一个 xml 文件,我只想从列表中读取二级元素。例如,我想要一个仅包含以下车辆的列表

车辆编号:“180”,类型:“BUS” 车辆编号:“190”,类型:“BUS”............

这是我的xml格式

<departures> 
 <station> 
  <vehicle> 
   <number>180</number> 
   <type>BUS</type> 
 </vehicle> 
 <vehicle> 
   <number>190</number> 
   <type>BUS</type> 
 </vehicle> 
 </station> 
 <station>  
 <vehicle> 
  <number>290</number> 
  <type>BUS</type> 
 </vehicle> 
 <vehicle> 
   <number>380</number> 
   <type>BUS</type> 
  </vehicle> 
 </station> 
<departures>

这是javascript部分

$(document).ready(function(){
            $.ajax({
                type: "GET",
                url: XML_PATH,
                dataType: "xml",
                success: function(xml) {
                $("#update-target").empty();
                $(xml).find("station").each(function () {
                      $("#update-target").append('<ul>');                        
                        $(this).find("vehicle").each(function () {
                         var number = $(this).find('number').text();
                         var type = $(this).find('type').text();
                            $("#update-target ul").append('<li>' + type + number + '</li>');
                        });
                    });
                    },  
        });
    });

在运行上面的代码时,我没有得到任何输出。请问什么是正确的方法来做到这一点。谢谢

4

1 回答 1

0

The code in your question always appends the current list item to all the <ul> elements under #update-target, because that's what #update-target ul matches.

That does not explain why you're not getting any output at all, but your comment indicates you might want to have a solution for this problem too.

A simple answer is to use the :last selector to only append list items to the last <ul> element:

$("#update-target ul:last").append("<li>" + type + number + "</li>");

To elaborate a little more, you can also try using another paradigm. You want to build DOM elements from the XML markup you receive, which means you want to project some data (XML markup) into other data (DOM elements). In this situation, map() can be used instead of each() to project data instead of iterating over it, which is closer to functional programming:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: XML_PATH,
        dataType: "xml",
        success: function(xml) {
            $("#update-target").empty()
                               .append($(xml).find("station").map(function() {
                return $("<ul>").append($(this).find("vehicle").map(function() {
                    var $this = $(this);
                    return $("<li>").text($this.find("type").text()
                        + $this.find("number").text());
                }));
            }));
        }
    });
});

This way, you don't have to bother matching the current <ul> element in the first place, as it becomes part of your current context.

于 2012-07-13T19:24:52.030 回答