xcode.png
XML文件解析實(shí)例(NSXMLParser)
還是上一個(gè)Demo的要求玛追,只是將解析方式由JSON變成XML,那又該如何解析呢俱萍?代碼如下:
#import "ViewController.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "WJCellItem.h"
#import <MediaPlayer/MediaPlayer.h>
#import "WJTableViewCell.h"
@interface ViewController ()<NSXMLParserDelegate>
@property (strong,nonatomic)NSMutableArray *dataArr;
@end
@implementation ViewController
-(NSMutableArray *)dataArr{
if (_dataArr==nil) {
_dataArr=[NSMutableArray array];
}
return _dataArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
//獲取請(qǐng)求路徑
NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
//創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//創(chuàng)建會(huì)話對(duì)象
NSURLSession *session=[NSURLSession sharedSession];
//根據(jù)會(huì)話對(duì)象創(chuàng)建請(qǐng)求任務(wù)
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//創(chuàng)建XML解析器
NSXMLParser *parser=[[NSXMLParser alloc]initWithData:data];
//設(shè)置代理
parser.delegate=self;
//開始解析
[parser parse];
//由于NSURLSession處理任務(wù)的操作默認(rèn)都是在子線程中進(jìn)行的端壳,而像刷新數(shù)據(jù)設(shè)置圖片這種操作必須在主線程中進(jìn)行,因此必須進(jìn)行線程間的通信枪蘑,轉(zhuǎn)到主隊(duì)列损谦,執(zhí)行UI操作
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
[self.tableView reloadData];
}];
}];
//發(fā)送請(qǐng)求
[dataTask resume];
}
//一共有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArr.count;
}
//每一個(gè)cell的內(nèi)容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *ID=@"cell";
//cell的重用機(jī)制
WJTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (cell==nil) {
cell=[[WJTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//根據(jù)行號(hào)來提取模型,并設(shè)置數(shù)據(jù)
WJCellItem *item=self.dataArr[indexPath.row];
cell.textLabel.text=item.name;
cell.detailTextLabel.text=[NSString stringWithFormat:@"播放數(shù)量為:%@",item.length];
//拼接路徑
NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.image];
//利用框架來下載并設(shè)置圖片
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"xcode"]];
return cell;
}
//當(dāng)點(diǎn)擊cell時(shí)回來到這個(gè)方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//拿到模型
WJCellItem *item=self.dataArr[indexPath.row];
//拼接路徑
NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.url];
NSURL *url=[NSURL URLWithString:path];
//創(chuàng)建一個(gè)能播放視頻的控制器實(shí)例
MPMoviePlayerViewController *vc=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
[self presentViewController:vc animated:YES completion:nil];
}
//開始解析某一個(gè)元素的時(shí)候調(diào)用腥寇,會(huì)多次調(diào)用
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{
//解析的時(shí)候忽略根元素
if ([elementName isEqualToString:@"videos"]) {
return;
}
[WJCellItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{@"ID":@"id"};
}];
//將字典轉(zhuǎn)換成模型
WJCellItem *item=[WJCellItem mj_objectWithKeyValues:attributeDict];
[self.dataArr addObject:item];
}
//某個(gè)元素解析完畢的時(shí)候調(diào)用,會(huì)多次調(diào)用
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
}
//整個(gè)XML文檔解析結(jié)束的時(shí)候調(diào)用
-(void)parserDidEndDocument:(NSXMLParser *)parser{
}
@end
XML文件解析實(shí)例(GDataXML)
#import "ViewController.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "WJCellItem.h"
#import <MediaPlayer/MediaPlayer.h>
#import "WJTableViewCell.h"
#import "GDataXMLNode.h"
@interface ViewController ()
@property (strong,nonatomic)NSMutableArray *dataArr;
@end
@implementation ViewController
-(NSMutableArray *)dataArr{
if (_dataArr==nil) {
_dataArr=[NSMutableArray array];
}
return _dataArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
//獲取請(qǐng)求路徑
NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
//創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//創(chuàng)建會(huì)話對(duì)象
NSURLSession *session=[NSURLSession sharedSession];
//根據(jù)會(huì)話對(duì)象創(chuàng)建請(qǐng)求任務(wù)
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//加載整個(gè)XML文檔
GDataXMLDocument *doc=[[GDataXMLDocument alloc]initWithData:data options:kNilOptions error:nil];
//到根元素 根據(jù)根元素得到內(nèi)部所有名稱為video的子元素
NSArray *eles= [doc.rootElement elementsForName:@"video"];
//03 遍歷所有的子元素,得到子元素中的屬性
for (GDataXMLElement *ele in eles) {
WJCellItem *video = [[WJCellItem alloc]init];
video.ID = [ele attributeForName:@"id"].stringValue;
video.image = [ele attributeForName:@"image"].stringValue;
video.length = [ele attributeForName:@"length"].stringValue;
video.name = [ele attributeForName:@"name"].stringValue;
video.url = [ele attributeForName:@"url"].stringValue;
[self.dataArr addObject:video];
}
//由于NSURLSession處理任務(wù)的操作默認(rèn)都是在子線程中進(jìn)行的成翩,而像刷新數(shù)據(jù)設(shè)置圖片這種操作必須在主線程中進(jìn)行觅捆,因此必須進(jìn)行線程間的通信赦役,轉(zhuǎn)到主隊(duì)列,執(zhí)行UI操作
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
[self.tableView reloadData];
}];
}];
//發(fā)送請(qǐng)求
[dataTask resume];
}
//一共有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArr.count;
}
//每一個(gè)cell的內(nèi)容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *ID=@"cell";
//cell的重用機(jī)制
WJTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
if (cell==nil) {
cell=[[WJTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
//根據(jù)行號(hào)來提取模型栅炒,并設(shè)置數(shù)據(jù)
WJCellItem *item=self.dataArr[indexPath.row];
cell.textLabel.text=item.name;
cell.detailTextLabel.text=[NSString stringWithFormat:@"播放數(shù)量為:%@",item.length];
//拼接路徑
NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.image];
//利用框架來下載并設(shè)置圖片
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"xcode"]];
return cell;
}
//當(dāng)點(diǎn)擊cell時(shí)回來到這個(gè)方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//拿到模型
WJCellItem *item=self.dataArr[indexPath.row];
//拼接路徑
NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.url];
NSURL *url=[NSURL URLWithString:path];
//創(chuàng)建一個(gè)能播放視頻的控制器實(shí)例
MPMoviePlayerViewController *vc=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
[self presentViewController:vc animated:YES completion:nil];
}
@end
注意:有關(guān)GDataXMLNode的配置:
- 1.打開.h文件掂摔,復(fù)制/usr/include/libxml2 然后去build Setting中找header serach 點(diǎn)擊右側(cè)添加復(fù)制的內(nèi)容
- 2.復(fù)制.h里的-lxml2 然后去build Setting里搜索other linker 同樣是點(diǎn)擊右側(cè),添加復(fù)制內(nèi)容
- 3.將GData類設(shè)置為arc混編赢赊,先嘗試點(diǎn)擊Edit-->Convert-->To Objective Arc,如果成功再去找到Build phasses-->compile Sources-->GDataXMLNode-->雙擊右側(cè)添加內(nèi)容:-fno-objc-arc