问题
I have an NSDictionary that was converted from XML that is really confusing me. If you could take a look and let me know the best method of getting the objects for the key class_id, I would really appreciate it.
{
response= {
"@status" = ok;
rosters = {
"@page" = 1;
"@page_count" = 1;
"@records_per_page" = 50;
"@total_record_count" = 8;
roster = (
{
"@class_id" = 0001;
"@role" = 0;
"@user_id" = 12345;
class= {
"@active" = false;
"@name" = NAME;
}
}
{
"@class_id" = 0002;
"@role" = 0;
"@user_id" = 12345;
}
{
"@class_id" = 0003;
"@role" = 0;
"@user_id" = 12345;
}
);
}
}
}
All I am wanting to do is either set up variables for the individual class_id's or put all of the class_id's in an NSArray. I've been reading the apple documentation and have tried every method I can think of, but it either crashes with nsexception or returns no data. Thanks so much for your help.
Ok let's just backup a minute. It would appear that the XMLReader plugin that I used to convert this to an NSDictionary is making this far more complicated than it needs to be. Here is the original XML data.
<response status="ok">
<rosters page_count="1" page="1" records_per_page="50" total_record_count="7">
<roster class_id="0001" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0002" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0003" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0004" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0005" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0006" role="S" user_id="91563" roster_id="ID"/>
<roster class_id="0007" role="S" user_id="91563" roster_id="ID"/>
</rosters>
</response>
Can anyone suggest a simple way to just grab the class_id values? Is converting to NSDictionary a reasonable way to do it? I just need the data as separate variables or an NSArray.
回答1:
Don't worry about the "best method". Just use a method that won't be confusing to revisit later and lets you move on to more important things.
NSMutableArray *classIds = [NSMutableArray array];
NSDictionary *rosterArray = [convertedXmlDictionary valueForKeyPath:@"response.rosters.roster"];
for (NSDictionary *roster in rosterArray) {
[classIds addObject:[roster objectForKey:@"@class_id"]];
}
来源:https://stackoverflow.com/questions/8751198/complex-nsdictionary-taken-objectsforkeys-and-sorting-them-as-nsarray-or-separa