首页投稿(暂停使用,暂停投稿)iOS开发iOS Developer

iOS-->XML文件的两种解析方式

2016-07-19  本文已影响415人  奕十八
xcode.png

XML文件解析实例(NSXMLParser)

还是上一个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];
    //获取请求路径
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象创建请求任务
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //创建XML解析器
        NSXMLParser *parser=[[NSXMLParser alloc]initWithData:data];
        //设置代理
        parser.delegate=self;
        //开始解析
        [parser parse];

        //由于NSURLSession处理任务的操作默认都是在子线程中进行的,而像刷新数据设置图片这种操作必须在主线程中进行,因此必须进行线程间的通信,转到主队列,执行UI操作
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.tableView reloadData];
        }];

    }];
    //发送请求
    [dataTask resume];

    }
//一共有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
//每一个cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   static NSString *ID=@"cell";
    //cell的重用机制
    WJTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[WJTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    //根据行号来提取模型,并设置数据
    WJCellItem *item=self.dataArr[indexPath.row];
    cell.textLabel.text=item.name;
    cell.detailTextLabel.text=[NSString stringWithFormat:@"播放数量为:%@",item.length];
    //拼接路径
    NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.image];
    //利用框架来下载并设置图片
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"xcode"]];
    return cell;
}
//当点击cell时回来到这个方法
-(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];
    //创建一个能播放视频的控制器实例
    MPMoviePlayerViewController *vc=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
    [self presentViewController:vc animated:YES completion:nil];
}
//开始解析某一个元素的时候调用,会多次调用
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{
    //解析的时候忽略根元素
    if ([elementName isEqualToString:@"videos"]) {
        return;
    }

    [WJCellItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{@"ID":@"id"};
        }];
//将字典转换成模型
    WJCellItem *item=[WJCellItem mj_objectWithKeyValues:attributeDict];
    [self.dataArr addObject:item];
}
//某个元素解析完毕的时候调用,会多次调用
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{


}
//整个XML文档解析结束的时候调用
-(void)parserDidEndDocument:(NSXMLParser *)parser{



}
@end

XML文件解析实例(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];
    //获取请求路径
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象创建请求任务
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       //加载整个XML文档
        GDataXMLDocument *doc=[[GDataXMLDocument alloc]initWithData:data options:kNilOptions error:nil];
        //到根元素 根据根元素得到内部所有名称为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处理任务的操作默认都是在子线程中进行的,而像刷新数据设置图片这种操作必须在主线程中进行,因此必须进行线程间的通信,转到主队列,执行UI操作
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.tableView reloadData];
        }];

    }];
    //发送请求
    [dataTask resume];

    }
//一共有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
//每一个cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   static NSString *ID=@"cell";
    //cell的重用机制
    WJTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[WJTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    //根据行号来提取模型,并设置数据
    WJCellItem *item=self.dataArr[indexPath.row];
    cell.textLabel.text=item.name;
    cell.detailTextLabel.text=[NSString stringWithFormat:@"播放数量为:%@",item.length];
    //拼接路径
    NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.image];
    //利用框架来下载并设置图片
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"xcode"]];
    return cell;
}
//当点击cell时回来到这个方法
-(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];
    //创建一个能播放视频的控制器实例
    MPMoviePlayerViewController *vc=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
    [self presentViewController:vc animated:YES completion:nil];
}
@end

注意:有关GDataXMLNode的配置:

上一篇 下一篇

猜你喜欢

热点阅读