Reputation: 43
I want to use a web service and grab the data from the service. I am able to send the request and receive the data but help me with parsing it. heres my code. I want to parse the XML response and store it in a array for further use
-(void)performSearch:(NSString *)searchText
{
NSString *param = [NSString stringWithFormat:@"ZIP=%@",
searchText];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?%@", param]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded"];
NSLog(@"%@",param);
NSLog(@"%@",url);
NSLog(@"%@",request);
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *response = [request responseData];
NSLog(@"%@",response);
help me how to parse the data and store it in array
//NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:response];
}
Upvotes: 0
Views: 5867
Reputation: 5061
There are plenty of good tutorials for learning how to properly parse XML, here's a quickie:
in .h
@interface ObjectName : ObjectSuperclass <NSXMLParserDelegate> {
NSMutableString *currentElement;
NSMutableString *childElement;
NSMutableDictionary *array;
NSXMLParser *parser;
}
@end
in .m:
-(void)parseWithData:(NSData *)data {
parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
//You might want to consider additional params like:
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
//And then finally (which activates the delegates):
[parser parse];
}
Again in .m, insert these NSXMLParser Delegate Methods:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = nil;
currentElement = [elementName copy];
if ([elementName isEqualToString:@"xmlParentElement"]) {
//This means the parser has entered the XML parent element named: xmlParentElement
//All of the child elements that need to be stored in the array should have their own IVARs and declarations.
childElement = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//For all child elements, run this if statement.
if (currentElement isEqualToString:@"childElement") {
[childElement appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"xmlParentElement"]) {
[array addObject:childElement];
}
}
Feel free to comment if things are unclear!
Upvotes: 1