iOSiOS

iOS SAX- NSXMLParser解析

2015-11-12  本文已影响1344人  iOS_成才录

1、使用步骤

// 传入XML数据,创建解析器
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
// 设置代理,监听解析过程
parser.delegate = self;
// 开始解析
[parser parse];

2、NSXMLParser解析特点

3、NSXMLParserDelegate代理

- (void)parserDidStartDocument:(NSXMLParser *)parser
- (void)parserDidEndDocument:(NSXMLParser *)parser
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

4、NSXMLParser解析小案例

#import "ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <MediaPlayer/MPMoviePlayerViewController.h>
#import "XMGVideo.h"
#import <MJExtension/MJExtension.h>

@interface ViewController ()<NSXMLParserDelegate>
@property (nonatomic, strong) NSMutableArray *videos; /**< 视屏信息 */
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 只需要在字典转模型之前, 告诉框架要将模型中的哪个属性和字典中的哪个KEY对应
    [XMGVideo setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{@"ID":@"id"};
    }];

    self.tableView.rowHeight = 150;
    // Do any additional setup after loading the view, typically from a nib.
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

        // 1.根据需要解析的XML数据, 创建NSXMLParser对象
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

        // 2.设置代理, 通过代理方法告诉NSXMLParser, 需要获取哪些元素和哪些属性
        parser.delegate = self;

        // 2.开始解析
        [parser parse];
    }];
}
#pragma mark - NSXMLParserDelegate
// 只要开始解析XML文档就会调用
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"DidStartDocument");
}
// 只要解析完毕XML文档就会调用
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
     NSLog(@"DidEndDocument");
    // 刷新UI
    [self.tableView reloadData];
}
// 只要开始解析一个元素就会调用
// elementName : 元素名称
// attributeDict : 元素中的属性
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    // videos
    // video
//    NSLog(@"%@", elementName);
//    NSLog(@"%@", attributeDict);

    if ([elementName isEqualToString:@"videos"]) {
        return;
    }
    XMGVideo *video = [XMGVideo objectWithKeyValues:attributeDict];
    [self.videos addObject:video];
}

// 只要解析完一个元素就会调用
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
     // video
     // videos
//     NSLog(@"%@", elementName);
}
// 解析出现错误时调用
- (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError
{
    NSLog(@"error");
}

#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    // 2.取出对应行的字典
    XMGVideo *video = self.videos[indexPath.row];
    // 2.1设置数据
    cell.textLabel.text = video.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%@", video.length];
    NSString *urlStr = [NSString stringWithFormat:@"http://120.25.226.186:32812/%@", video.image];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil];

    // 3.返回cell
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.取出选中行对应的字典
    XMGVideo *video = self.videos[indexPath.row];
    // 2.根据字典中的URL属性拼接视屏的地址
    NSString *urlStr = [NSString stringWithFormat:@"http://120.25.226.186:32812/%@", video.url];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    // 3.播放视屏
    MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    // 4.显示控制器
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - lazy
- (NSMutableArray *)videos
{
    if (!_videos) {
        _videos = [NSMutableArray array];
    }
    return _videos;
}
@end
上一篇下一篇

猜你喜欢

热点阅读