views:

606

answers:

2

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 funtion????

+2  A: 

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();
Paolo Bergantino
since i dont the names...i used this code instead...two different arrays for count and names....$('resultGroups', $(xml)).each(function() { var count = $('results', this).length; var name = $('name',this).text(); resultGroupNames[i] = name; resultsNo[i] = count; i++; });i got the counts correctly. but in case of names it stores all the names inside the resultGroup tags....ie names tags inisde subgroup results etc.. i want only the name tag directly inside resultGroup...
Jasim
Tht one works without problem....thnx for that
Jasim
A: 

this was very useful for me! thanks!!!

var groups = {}; $('resultGroups', $(xml)).each(function() { var count = $('results', this).length; var name = $('name',this).text(); groups[name] = count; });

kcobuntu