//sax标签对解析
{
NSMutableArray *_userArray;
User *_user;
NSMutableString *_buffer;//缓存器
}
//设置请求路劲
NSURL*url = [NSURL URLWithString:@"http://localhost:8080/Login/NewServlet?command=3"];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURL RequestrequestWithURL:url];
//设置请求方式不设置默认为GET请求方式
//[request setHTTPMethod:@"POST"];
//设置请求参数
//[request setHTTPBody:[@"command=3" dataUsingEncoding:NSUTF8StringEncoding]];
//发送请求,建立连接
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *_Nullableresponse,NSData *_Nullabledata,NSError *_NullableconnectionError) {
NSLog(@"data ---- %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//专门解析XML的类--- sax dom
//sax标签对
//创建解析类对象
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
//导入协议,设置代理
parser.delegate = self;
//开始解析
[parser parse];
}];
}
#pragma mark --- NSXMLParserDelegate
//开始解析
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"---开始解析---");
_userArray= [[NSMutableArray alloc] init];
_buffer= [[NSMutableString alloc] init];
}
//找到一个开始标签
- (void)parser:(NSXMLParser *)parser didStartElement:(nonnullNSString *)elementName namespaceURI:(nullableNSString *)namespaceURI qualifiedName:(nullableNSString *)qName attributes:(nonnullNSDictionary *)attributeDict {
NSLog(@"开始标签----%@",elementName);
if([elementName isEqualToString:@"friend"]) {
_user= [[User alloc] init];
}
}
//找到一个值调用
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"值调用----%@",string);
//如果数据过多,分多次返回,要拼接数据
[_buffer appendString:string];
}
//找到一个结束标签调用
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString*) namespaceURI qualifiedName:(NSString*)qName{
NSLog(@"结束标签----%@",elementName);
if([elementName isEqualToString:@"name"]) {
_user.name = _buffer;
} elseif ([elementName isEqualToString:@"pwd"]){
_user.pwd = _buffer;
} elseif ([elementName isEqualToString:@"trueName"]){
_user.tureName = _buffer;
} elseif ([elementName isEqualToString:@"age"]){
_user.age=_buffer;
} elseif ([elementName isEqualToString:@"friend"]) {
[_userArray addObject:_user];
//用完之后释放
_user = nil;
}
//清空数据,以便后续取值
[_buffer setString:@""];
}
//结束解析
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"---结束解析---");
NSLog(@"---------%ld",_userArray.count);
for(User * user in _userArray) {
NSLog(@"-----%@",user.name);
}
}