Reputation: 12897
I have an XML like this
<resultGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<name> </name>
</resultGroups>
<resultGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<name> </name>
</resultGroups>
I have this code to select number of results inside each resultGroup
$('resultGroups', $(xml)).each(function() {
count = $('results', this).length;
arr[i] = count;
i++;
});
What I want is to get the name from each resultGroup tag and store it in an array.
How can I do that inside the above code?
How can I select only the name tag of the first resultGroup only without .each function?
Upvotes: 0
Views: 3363
Reputation: 488694
If your XML looks like this:
<resultGroups>
<subGroups>
<results> </results>
</subGroups>
<subGroups>
<results> </results>
</subGroups>
<name>myname</name>
</resultGroups>
<resultGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<subGroups>
<results> </results>
<results> </results>
</subGroups>
<name>othername</name>
</resultGroups>
Using this code:
var groups = {};
$('resultGroups', $(xml)).each(function() {
var count = $('results', this).length;
var name = $('name',this).text();
groups[name] = count;
});
After that, groups will be a dictionary (object, hence the {}) like so:
{'myname': 2, 'othername': 4}
Which you can access by doing groups.myname
or groups['myname']
To get only the name tags directly in resultGroups tag - I didn't see any other in the example code, so I didn't know there were more - use this code instead:
var name = $(this).children('name').text();
Upvotes: 3