Andromeda
Andromeda

Reputation: 12897

XML parsing in Jquery

I have an XML file which has four <resutGroups> tag:

<resultGroups>
  <subGroups>
    <name> </name>
  </subGroups>
  <name> </name>
</resultGroups>

each <resultGroup> has several <subGroups> and each <subGroups> has <name> tag.

I want to select only the name tag of <resultGroups> only

$(xml).find("resultGroups").each(function() {
  alert( $(this).find("name").text() ); 
}

When I use the above code it returns all the names inside the <resultgroups> and <subGroups>.

How can I select only one <name> which is in the <resultGroups> tag?

Upvotes: 1

Views: 3917

Answers (1)

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

You have a couple of options:

var xml = $(xml);
$('resultGroups > name', xml).each(function() {
    alert($(this).text());
});

This uses the direct descendant selector. You could also use children, which does the same thing:

$('resultGroups', xml).children('name').each(function() {
    alert($(this).text());
});

Upvotes: 8

Related Questions