Search code examples
javascriptxmllistparsingunordered

How to insert an XML object into an unordered list


i just asked a very similar question but wiht Json, now i'm having trouble with 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>

I want to put the names into an unsorted list

My code:

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>";
            }
        }
    }

This outputs absolutely nothing, could somebody show me where i went wrong? Please and thank you


Solution

  • Try this:

    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>";
            });   
        });
    });