0

我刚刚问了一个非常相似的问题,但是使用 Json,现在我遇到了 xml 问题。

XML:

<dinosaurs>
 <dinosaur>
  <name>Staurikosaurus</name>
  <group>Saurischia</group>
  <diet>Carnivore</diet>
  <period>Triassic</period>
 </dinosaur>
 <dinosaur>
  <name>Diplodocus</name>
  <group>Saurischia</group>
  <diet>Herbivore</diet>
  <period>Jurassic</period>
 </dinosaur>
 <dinosaur>
  <name>Stegosaurus</name>
  <group>Ornithischia</group>
  <diet>Herbivore</diet>
  <period>Jurassic</period>
 </dinosaur>
 <dinosaur>
  <name>Tyrannosaurus</name>
  <group>Saurischia</group>
  <diet>Carnivore</diet>
  <period>Cretaceous</period>
 </dinosaur>
 </dinosaurs>

我想将名称放入未排序的列表中

我的代码:

var inner = '';
    $(xml).find('dinosaurs').each(function(){
        $(this).find('dinosaur').each(function(){
            $(this).find("name").each(function(){
             var name = $(this).text();
             inner += "<li>"+name+"</li>";
            }
        }
    }

这绝对没有输出,有人可以告诉我我哪里出错了吗?谢谢,麻烦您了

4

1 回答 1

0

尝试这个:

var xml = "<dinosaurs> <dinosaur>  <name>Staurikosaurus</name>  <group>Saurischia</group>  <diet>Carnivore</diet>  <period>Triassic</period> </dinosaur> <dinosaur>  <name>Diplodocus</name>  <group>Saurischia</group>  <diet>Herbivore</diet>  <period>Jurassic</period> </dinosaur> <dinosaur>  <name>Stegosaurus</name>  <group>Ornithischia</group>  <diet>Herbivore</diet>  <period>Jurassic</period> </dinosaur> <dinosaur>  <name>Tyrannosaurus</name>  <group>Saurischia</group>  <diet>Carnivore</diet>  <period>Cretaceous</period> </dinosaur> </dinosaurs>";

var xmlDoc = $.parseXML(xml);

var inner = '';
$(xmlDoc).find('dinosaurs').each(function ()
{
    $(this).find('dinosaur').each(function ()
    {
        $(this).find("name").each(function ()
        {
            var name = $(this).text();
            inner += "<li>" + name + "</li>";
        });   
    });
});
于 2014-04-11T02:06:44.340 回答