4

现在我想使用 AFNetworking 库来获取 XML 内容,所以我使用这段代码

AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request 
success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) 
{
    XMLParser.delegate = self;
    [XMLParser parse];
} 
failure:nil];
[operation start];

我的问题是知道是否有任何方法可以获取 xml 响应的内容(我想用 NSLog 打印 xml 内容)

提前致谢

4

2 回答 2

8

来自请求的原始数据始终在responseData操作类的属性中可用。以下是您将如何展示它NSLog

__block AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://legalindexes.indoff.com/sitemap.xml"]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
    NSLog(@"Parser: %@", XMLParser);
    NSLog(@"Raw XML Data: %@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
    NSLog(@"Failure!");
}];

[operation start];

也就是说,标准AFXMLRequestOperation类使用NSXMLParser起来很痛苦。如果您的有效负载不是太大并且性能不是问题,我建议您使用 Mattt 的新AFKissXMLRequestOperation类,它将为您进行解析并公开一个更友好的NSXMLDocument兼容对象:

__block AFKissXMLRequestOperation *operation = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://legalindexes.indoff.com/sitemap.xml"]] success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument) {
    NSLog(@"XMLDocument: %@", XMLDocument);
    NSLog(@"Raw XML Data: %@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) {
    NSLog(@"Failure!");
}];

[operation start];
于 2013-03-25T12:46:50.357 回答
2

我相信 AFXMLRequestOperation 是 SAX 操作。即,xml 响应不是在一堆中收到的(它一直在接收直到完成)。

您可以打印通过打印接收到的完整数据string

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 

或将字符串附加到 ivar 并在其上打印parserDidEndDocument

- (void) parserDidEndDocument: (NSXMLParser *)parser

如果您正在尝试测试 api 以查看返回。我用这个方法

[[AFHTTPClient sharedClient] postPath:url
                              parameters:nil 
                                 success:^( AFHTTPRequestOperation *operation , id responseObject ) {
                                     NSLog(@"responseobject: %@", [responseObject description]);
                                     }
                                     failure:^( AFHTTPRequestOperation *operation , NSError *error ){
                                        NSLog(@"Handle failure for me");
                                     }
                                     ]];
于 2012-07-06T07:55:22.407 回答