Http Get a plist in XML format to an array or to file, then to an array?
I'm replacing a simple initWithContentsOfURL: with a dynamic HttpGet where I pass two parameters and that webpage returns the exact same data as XML in text format.
Must I really parse the data to get it into an array of dictionaries? I was hoping for NSXMLParser initWithData: and then some automated way of initalizing an NSArray with all nodes, structure following the XML. (It is a plist in XML format, so the structure and all key names are already in it. Why should I have to write a replica of all that in Objective-C as well?!)
I'd be happy with httpgetting to a text file and then NSArray initWithContentsOfFile.
Edit: This yields an NSData object 26K in size, but the error message "Conversion of the string failed. The string is empty".
//Initiate connection
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:url(aspurl)];
[request setHTTPMethod:@"GET"];
//keep adding your headers this way
NSString *accept = [NSString stringWithFormat:@"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/*;q=0.5"];
[request addValue:accept开发者_开发知识库 forHTTPHeaderField: @"Accept"];
//send request & get response
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *errString;
NSMutableArray *arr=[NSPropertyListSerialization propertyListFromData:returnData
mutabilityOption:NSPropertyListMutableContainers
format: NULL
errorDescription:&errString];
if (errString)
{
NSLog(@"%@",errString);
[errString release]; // exception to the rules
}
This gives the error "Conversion of string failed. The string is empty." and arr is 0x0.
Can anyone point out my mistake?
First-off, you could use a class like XML-to-NSDictionary to do the parsing, and it could be dead simple, but it seems you don't like that approach.
Since you are dealing with a plist, as an alternative, you can:
- use
NSURLConnection
to load the plist into anNSData
; - use
[NSPropertyListSerialization propertyListFromData:mutabilityOption:format:errorDescription:method]
to convert that into anNSDictionary/NSArray
;
Have also a look at Property List Programming Guide.
精彩评论