2

我在我的应用程序上解析一个 webService 响应 (XML),我意识到并不是所有的答案都被解析(我预计至少还有 3 个相同信息的块),所以我决定像这样修改我的方法 connectionDidFinishLoading:

-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSString *XMLResponse = [[NSString alloc]initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    NSLog(@"xml message: %@, data length: %i", XMLResponse, [webData length]);

    if ([XMLResponse hasPrefix:@"[ERR]"]){
        [[[UIAlertView alloc]initWithTitle:@"Notification"
                                   message:XMLResponse != nil ? [@"there was an error while trying to load service" stringByAppendingString:XMLResponse]: @"there was an error while trying to load service"
                                  delegate:self
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil]show];
        _transacWebServCompleto = @"FALSE";
        return;
    }

    xmlParser = [[NSXMLParser alloc] initWithData:webData];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
}

在我运行我的应用程序时,我在输出部分得到了这个

xml message: (null), data length: 5516

该表打印正确但不完全,我的 XML 显示为 null 但由于数据长度,它包含数据,任何帮助我将不胜感激

提前致谢

4

1 回答 1

2

您的 XML 可能包含特殊字符,例如重音词,请尝试以下操作:

-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSString *XMLResponse = [[NSString alloc]initWithBytes:[webData mutableBytes] length:[webData length] encoding:NSISOLatin1StringEncoding];

    NSLog(@"xml message: %@, data length: %i", XMLResponse, [webData length]);

    if ([XMLResponse hasPrefix:@"[ERR]"]){
        [[[UIAlertView alloc]initWithTitle:@"Notification"
                                   message:XMLResponse != nil ? [@"there was an error while trying to load service" stringByAppendingString:XMLResponse]: @"there was an error while trying to load service"
                                  delegate:self
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil]show];
        _transacWebServCompleto = @"FALSE";
        return;
    }

    xmlParser = [[NSXMLParser alloc] initWithData:[XMLResponse dataUsingEncoding:NSUTF8StringEncoding]];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
}

我所做的只是:

  1. 获取您的 NSString (XMLResponse) 并将编码更改为 NSISOLatin1StringEncoding
  2. 通过使用您的 NSString (XMLResponse) 一步创建 NSData 对象来初始化您的 NSXMLParser 对象(解析),但现在使用 NSUTF8StringEncoding 进行编码

试试看,告诉我们进展如何!

于 2013-08-22T01:06:28.797 回答