用jQuery解析XML……问题检索元素。

时间:2021-07-13 20:33:39

An XML snippet:

XML片段:

<results>
   <review>
      <api_detail_url>http://api.giantbomb.com/review/1/</api_detail_url>
      <game>
         <api_detail_url>http://api.giantbomb.com/game/20462/</api_detail_url>
         <id>20462</id>
         <name>SingStar</name>
      </game>
      <score>4</score>
   </review>
</results>

And here's my testing code, just to show whether data is being collected or not ('data' holds the XML):

这是我的测试代码,只是为了显示数据是否被收集('data'持有XML):

var element;

$(data).find('review').each(function() {
    element = $(this).find('name').text();
});

alert(element); 

Now here's the problem, only this query actually returns data:

问题是,只有这个查询返回数据:

$(this).find('score').text();

The alert box in this case would pop up with '4'. These two other queries don't return anything (the alert box is blank):

在这个情况下,警告框会弹出“4”。这两个查询不返回任何内容(警告框为空):

$(this).find('api_detail_url').text();
$(this).find('name').text();

I've tried using jQuery selectors, like...

我尝试过使用jQuery选择器,比如……

$(this).find('game > name').text();

...but that doesn't work, either, still get a blank alert box. Am I missing something? Testing is being done in Chrome.

…但这也不管用,仍然会得到一个空白的警告框。我遗漏了什么东西?测试正在Chrome中进行。

1 个解决方案

#1


0  

Try something like this:

试试这样:

assuming that in xml you have the xml document

假设在xml中有xml文档

$(xml).each(function (index, item) {
    $reviews = $(item).find('review');

    //assuming that you have more than one review in results
    $reviews.each(function (i, rev) {
        var api = $(rev).find('api_detail_url').text();
        var $game = $(rev).find('game');
        var gameApi = $game.find('api_detail_url').text();
        var gameID = $game.find('id').text();
        var gameName = $game.find('name').text();                     

    });

});

#1


0  

Try something like this:

试试这样:

assuming that in xml you have the xml document

假设在xml中有xml文档

$(xml).each(function (index, item) {
    $reviews = $(item).find('review');

    //assuming that you have more than one review in results
    $reviews.each(function (i, rev) {
        var api = $(rev).find('api_detail_url').text();
        var $game = $(rev).find('game');
        var gameApi = $game.find('api_detail_url').text();
        var gameID = $game.find('id').text();
        var gameName = $game.find('name').text();                     

    });

});