The HTTP protocol is the most common way for servers to communicate data with clients. In general, the data format is JSON, but in some cases XML. All JSON formats are parsed, so how do you parse XML?

This article is based on AFNetwork 3.2.1


To highlight

Typically, we make HTTP requests by instantiating an AfhttpsSessionManager object and setting some properties:

manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",nil]; Manager. RequestSerializer. TimeoutInterval = 30.0 f;

So here we’re not setting the responseServalizer property for the Manager, and the default responseServalizer is AFJSONResponseServalizer, so obviously we’re going to be requesting data in XML format, AFJsonResponseSerializer cannot be used. Here is the key code:

AFXMLParserResponseSerializer *response = [AFXMLParserResponseSerializer serializer];
manager.responseSerializer = response;

Some say it on the Internet

AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
response.acceptableContentTypes = [NSSet setWithObjects:@"text/xml", nil];
manager.responseSerializer = response;

This usage is not correct! ResponseSerializer type must be AFXMLParserResponseSerializer here, why can appear such solutions, may be because of a simple see error returned is “cannot receive text/XML data type” and guess the answer, It’s not tested; In other words, this method is available in lower versions of AFNetworking.

Use the following

[manager GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, Id _Nullable responseObject) {NSLog(@"LenovoID login result :%@",responseObject); NSXMLParser * XMLParser = responseObject; [xmlparser setDelegate:self]; [xmlparser parse]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {nSLog (@" Lenovoid login request failed :%@", [error localizedDescription]);}];

To implement the NSXMLParserDelegate protocol

#pragma mark-NSXMLParser delegate - (void)parserDidStartDocument:(NSXMLParser *)parser{NSLog(@"XML document start "); } -(void)parserDidEndDocument:(NSXMLParser *) Parser {NSLog(@" end of XML document "); } - (void)parser:(NSXMLParser *)parser foundElementDeclarationWithName:(NSString *)elementName model:(NSString *)model{ NSLog(@"elementName:%@",elementName); }

The use of NSXMLParser is indicated in Resources:

AFNetworking is the most basic iOS development technique, and the implementation Demo will not be presented here. The most important aspect of XML parsing is setup
AFHTTPSessionManagerThe object’s
responseSerializerAttribute values for