jquery xml loop though each node

armasmike
armasmike used Ask the Experts™
on
i am trying to loop though all the node one at a time. How do i count how many node are in the xml file

There are 7 <fromname>Chris Gannon </fromname>

i need it to count then display the first one and then the next time it loads display then the next one and so on.

How do i do that ?

// insert code for loaded event here
var fromName;
var outputField = $(this.lookupSelector("xmlOutput"));
var messageString;

$.ajax({	

	type: "GET",
	url: "sampleoutput.xml",
	dataType: "xml",
	success: function(xml) {

	  $(xml).find('greeting').each(function(){
             var name_text = $(this).find('fromname').text()
			 	
           
		messageString = "Hi "  +name_text + " ";
		outputField.html(messageString);

						 });	
				
	
				}
	});

Open in new window



and my xml

<?xml version="1.0" encoding="utf-8" ?>
<greeting>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  <fromname>Chris Gannon </fromname>
  
</greeting>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jon NormanInformation Systems Manager
Top Expert 2012

Commented:
$(this).find('fromname').length should give the number of elements.

$($(this).find('fromname')[2]) should be the third element (it's zero based)

you will need find someway of storing which one (index) you have displayed (maybe in a cookie) and then display the next.

Author

Commented:
I am using a program call Adobe edge it uses jquery as it's main code. Like ac3 is to flash i am trying try to recreate my flash animation that reads a xml file and display the text.

this works
$(this).find('fromname').length

but getting it to display one line at a time then do a +1 and go to the next line and so on.
Expert of the Year 2008
Top Expert 2008
Commented:
...then do a +1 ...
I don't know what you mean by that, if your intention for the "+1" is to find the next node in the "sequence/list", then there is no need to "+1" anything.  the $.each() will do the trick
try:
// insert code for loaded event here
var fromName;
var outputField = $(this.lookupSelector("xmlOutput"));
var messageString='';

$.ajax({	

	type: "GET",
	url: "sampleoutput.xml",
	dataType: "xml",
	success: function(xml) {
		var totalNodes=$(xml).find('fromname').size();

		$(xml).find('fromname').each(function(){
			var name_text = $(this).text();
			messageString += "Hi " + name_text + "<br />";
		});
		messageString += " Total: " + totalNodes;
		outputField.html(messageString);
	}
});

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial