我从Web服务中提取信息,我正在解析XML字符串,但在我的代码中,XML部分调用了4次,我不知道为什么。
这是我的代码;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Data has been loaded");
NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(@"Respose Data :%@",responseString) ;
NSData *xmlData = [responseString dataUsingEncoding:NSASCIIStringEncoding];
xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
// @"Element started %@",elementName);
currentElement=elementName;
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
count++;
if ([temp isEqualToString:@"true"]) {
[SVProgressHUD showSuccessWithStatus:@"Saved"];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loginPage) userInfo:nil repeats:NO];
}else{
[SVProgressHUD dismiss];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning"
message:@"Don't Save"
delegate:self
cancelButtonTitle:@"Okay"
otherButtonTitles:nil, nil];
[alertView show];
}
NSLog(@"count = %i",count);
currentElement=@"";
temp = @"";
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
temp = [temp stringByAppendingString:string];
}
这是我的XML返回字符串;
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><signUpResponse xmlns="http://tempuri.org/"><signUpResult>true</signUpResult></signUpResponse></s:Body></s:Envelope>
计数输出是; count = 1
count = 2
count = 3
count = 4
我做错了什么? 感谢您的回答和兴趣。
答案 0 :(得分:2)
xml中有4个结束标记,即</signUpResult></signUpResponse></s:Body></s:Envelope>
,并且在读取每个结束标记时将调用didEndElement方法,因此计数为4.
在您的情况下,您可以将代码包含在if语句中,以避免被调用4次。代码如下:
if([elementName isEqualToString:@"signUpResult"]){
if ([temp isEqualToString:@"true"]) {
[SVProgressHUD showSuccessWithStatus:@"Saved"];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loginPage) userInfo:nil repeats:NO];
}else{
[SVProgressHUD dismiss];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning"
message:@"Don't Save"
delegate:self
cancelButtonTitle:@"Okay"
otherButtonTitles:nil, nil];
[alertView show];
}
}