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

作者: 奕十八 | 来源:发表于2016-07-19 20:26 被阅读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的配置:

  • 1.打开.h文件,复制/usr/include/libxml2 然后去build Setting中找header serach 点击右侧添加复制的内容
  • 2.复制.h里的-lxml2 然后去build Setting里搜索other linker 同样是点击右侧,添加复制内容
  • 3.将GData类设置为arc混编,先尝试点击Edit-->Convert-->To Objective Arc,如果成功再去找到Build phasses-->compile Sources-->GDataXMLNode-->双击右侧添加内容:-fno-objc-arc

相关文章

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

    XML文件解析实例(NSXMLParser) 还是上一个Demo的要求,只是将解析方式由JSON变成XML,那又该...

  • Android 生成xml文件

    Android解析xml文件 两种方式生成: 1、通过StringBuffer直接以追加字符串的方式生成XML文件...

  • iOS-XML/JSON解析

    一、XML解析 XML解析有两种方式: DOM:一次性将整个XML文档加载进内存,比较适合解析小文件; SAX...

  • XMLSAX 和DOM解析数据

    //解析XML文件有两种方式: //1SAX解析:基于时间驱动的解析方式逐行解析(采用协议回调机制)解析过程若发现...

  • XML 解析

    XML三种解析方式: 下面简单说明下三种解析方式的使用 XML文件 新建xml文件food.xml 三种解析方式 ...

  • 解析XML文件有哪几种方式?

    以DOM方式解析XML文件; 以SAX方式解析XML文件; 转载自《猿圈》

  • iOS下XML文件的三种解析方式

    前言 在iOS开发中,数据解析通常有两种方式,一种是JSON解析,一种是XML解析。今天着重讲解一下XML文件解析...

  • java XML解析——DOM方式

    参照:XML解析——DOM方式Java文件操作①——XML文件的读取

  • Android15-XML和JSON解析

    1. XML解析的两种方式 服务器返回的XML数据如下 1.1使用Pull方式解析XML数据 使用Pull解析,首...

  • Swift - 解析XML格式数据(分别使用GDataXML和D

    XML解析方式的选择建议 大文件用:NSXMLParser 小文件用:GDataXML 假设需要被解析的XML数据...

网友评论

    本文标题:iOS-->XML文件的两种解析方式

    本文链接:https://www.haomeiwen.com/subject/wstvjttx.html