0

我想使用网络服务并从服务中获取数据。我能够发送请求并接收数据,但可以帮助我解析它。这是我的代码。我想解析 XML 响应并将其存储在数组中以供进一步使用

-(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];


     }
4

1 回答 1

1

有很多很好的教程来学习如何正确解析 XML,这里有一个快速的:

在.h

@interface ObjectName : ObjectSuperclass <NSXMLParserDelegate> {
    NSMutableString *currentElement;
    NSMutableString *childElement;
    NSMutableDictionary *array;
    NSXMLParser *parser;
}

@end

以 .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]; 
 }

再次在 .m 中,插入这些 NSXMLParser 委托方法:

- (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];
  }
}

如果事情不清楚,请随时发表评论!

于 2012-06-25T14:56:03.330 回答