Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of nodes in an XML snippet using Javascript/E4X

Consider this problem:

Using Javascript/E4X, in a non-browser usage scenario (a Javascript HL7 integration engine), there is a variable holding an XML snippet that could have multiple repeating nodes.

<pets>       
 <pet type="dog">Barney</pet>
 <pet type="cat">Socks</pet>
</pets>

Question: How to get the count of the number of pet nodes in Javascript/E4X ?

EDIT: To clarify, this question should be around E4X (ECMAScript for XML). Apologies to those who answered without this information. I should have researched & posted this info beforehand.

like image 672
p.campbell Avatar asked Jul 21 '09 22:07

p.campbell


2 Answers

Use an E4X XML object to build an XMLList of your 'pet' nodes. You can then call the length method on the XMLList.

//<pets>
//    <pet type="dog">Barney</pet>
//    <pet type="cat">Socks</pet>
//</pets>  

// initialized to some XML resembling your example
var petsXML = new XML("");  

// build XMLList
var petList = petsXML['pet'];  

// alternative syntax
// var petList = petsXML.pet;  

// how many pet nodes are under a given pets node?
var length = petList.length();
like image 87
csj Avatar answered Sep 25 '22 01:09

csj


I'd say... use jQuery!

  var count = 0;
  $(xmlDoc).find("pet").each(function() {
          count++;

          // do stuff with attributes here if necessary.
          // var pet = $(this);
          // var myPetType = pet.attr("type");
       };
  });

EDIT: Can't use jquery... ok, let's do it in regular javascript :(

      var pets= xmlDoc.getElementsByTagName("pet");
      for ( var i = 0; i < pets.length ; i++ )
      {
          count++;
         // var petObj = {
         //     pets[i].getAttribute("type")
         //  };
      }
like image 22
womp Avatar answered Sep 21 '22 01:09

womp