wicherqm
wicherqm

Reputation: 245

javascript jquery iterate simple XML

I need to iterate over XML items.

Sample XML:

<items>
    <name>234</name>
    <email></email>
    <phone></phone>
    <phone2></phone2>
    <phone7>33</phone7>
</items>

I tried a lot of combinations but without any success. For example:

var xml=' <items><name>234</name> <email></email><phone></phone></items>'

$(xml).find('items\').each(function() {
  alert($(this).text() + ':' + $(this).value());
}); 

Upvotes: 2

Views: 4210

Answers (3)

VoteyDisciple
VoteyDisciple

Reputation: 37803

The trouble is that in your example, <items>...</items> is the root node — it is the xml variable. So, if you want its children, you can just do:

var xml='<items><name>234</name> <email></email><phone></phone></items>';
$(xml).children.each(function() {
  alert(this.nodeName + ':' + $(this).text());
});

And if you want the <items> node itself, you can do simply:

var xml='<items><name>234</name> <email></email><phone></phone></items>';
$(xml).each(function() {
  alert(this.nodeName + ':' + $(this).text());
});

Upvotes: 3

Jim Schubert
Jim Schubert

Reputation: 20357

it should be:

$(xml).find('items').each(function(){
  var name = $(this).find('name').text();
  alert(name);
});

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

var xml=' <items><name>234</name> <email></email><phone></phone></items>';

$(xml).find('items').each(function() {
alert(this.nodeName + ':' + $(this).text());
}); 

Upvotes: 0

Related Questions