{
NSMutableArray *arr;
Model *mod;
//记录开始标签
NSString *new;
UITableView *tab;
}
#define MAC @"http://127.0.0.1/156.xml"
{ [super viewDidLoad]; NSURL *url=[NSURL URLWithString:MAC]; NSURLSession *se=[NSURLSession sharedSession]; NSURLSessionTask *task=[se dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //sax解析 NSXMLParser *par=[[NSXMLParser alloc]initWithData:data]; //设置代理 par.delegate=self; //开始解析 [par parse]; }]; //开始请求 [task resume]; tab=[[UITableView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width,self.view.frame.size.height)]; tab.dataSource=self; tab.delegate=self; [self.view addSubview:tab]; }//开始解析自动触发- (void)parserDidStartDocument:(NSXMLParser *)parser;{ //初始化 arr=[[NSMutableArray alloc]init];}//遇到开始标签自动触发- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary*)attributeDict;
{
if ([elementName isEqualToString:@"stu"]) {
//初始化对象
mod=[[Model alloc]init];
//添加数组
[arr addObject:mod];
}
//记录开始标签
new=elementName;
}
//遇到内容自动回调--空格或回车也会当做内容回调
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
if ([new isEqualToString:@"name"])
{
mod.name=string;
}
else if ([new isEqualToString:@"age"])
{
mod.age=string;
}
}
//遇到结束标签
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName;
{
//
new=nil;
}
//解析完毕
- (void)parserDidEndDocument:(NSXMLParser *)parser;
{
//刷新表格
[tab reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return arr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *str=@"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:str];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
}
Model*m=arr[indexPath.row];
cell.textLabel.text=m.name;
cell.detailTextLabel.text=m.age;
return cell;
}