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

Consider this problem:

Using Javascript / E4X, in a browser-free use case (Javascript HL7 integration mechanism), there is a variable containing an XML fragment that may have multiple duplicate nodes.

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

Question How to get Javascript / E4X pet node count?

EDIT: To clarify, this question should be around E4X (ECMAScript for XML) . I apologize to those who answered without this information. I had to study and publish this information in advance.

+6
javascript xml e4x mirth
source share
3 answers

Use the E4X XML object to create the XMLList of your home nodes. Then you can call the length method in 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(); 
+5
source share

I would 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: you cannot use jquery ... ok, let it be done in regular javascript: (

  var pets= xmlDoc.getElementsByTagName("pet"); for ( var i = 0; i < pets.length ; i++ ) { count++; // var petObj = { // pets[i].getAttribute("type") // }; } 
+3
source share

Using the DOM, you can call getElementsByTagName() .

 alert( document.getElementsByTagName( "pet" ).length ); 

Additional Information:

https://developer.mozilla.org/en/DOM:element.getElementsByTagName

You need to somehow get the XML document. XHR, for example, returns documents in the form of parsed XML.

 var xhr = new XMLHttpRequest(); xhr.open( 'GET', 'http://domain.com/pets.xml', true ); xhr.onreadystatechange = function ( e ) { if ( xhr.readyState == 4 && xhr.status == 200 ) alert( xhr.responseXML.getElementsByTagName( "pet" ).length ); }; xhr.send( null ); 
+3
source share

All Articles