NSXMLParser 解析xml详解

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#import "ViewController.h"
#import "Video.h"


@interface ViewController ()<NSXMLParserDelegate>
//存储对象数组
@property (nonatomic, strong) NSMutableArray *videos;
// 来回拼接
@property (nonatomic, strong) NSMutableString *elementString;
// 当前视频信息的对象
@property (nonatomic, strong) Video *video;
@end


@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 加载数据方法
    [self loadData];
}


#pragma mark - 加载数据
- (void)loadData
{
    // data
    NSString * path = [[NSBundle mainBundle] pathForResource:@"video.xml" ofType:nil];
    NSData * data = [NSData dataWithContentsOfFile:path];
        
    // 1>创建,传递data
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    
    // 2> 设置代理
    parser.delegate = self;
    
    // 3> 开始解析
    [parser parse];//返回值,判断是否解析成功
    
    // 4> 解析完成之后的操作
}


#pragma mark - XML解析代理方法
#pragma mark 1. 开始
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//    NSLog(@"开始解析文档");
    // 准备工作
    // 1> dataList
    self.videos = [NSMutableArray array];
    
    // 2> elementString
    self.elementString = [NSMutableString string];
}


#pragma mark 2. 所有开始一个节点:<element>
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"开始节点:=====%@ %@", elementName, attributeDict);
    // 如果是<video>新建对象
    if ([elementName isEqualToString:@"video"]) {
        self.video = [[Video alloc] init];
    }
    
    // 每开始一个新节点之前都清空elementString
    // 避免上一次的结果被重复拼接,例如拼完名字是"abc",再拼长度就会变成"vda1234"
    [self.elementString setString:@""];
}


#pragma mark 3. 查找内容,可能会重复多次
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    // 拼接字符串
    [self.elementString appendString:string];
}


#pragma mark 4. 节点结束 </element>
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//    NSLog(@"结束节点 %@", elementName);
    if ([elementName isEqualToString:@"name"])
    {
        self.video.name = self.elementString;
    }
    else if ([elementName isEqualToString:@"length"])
    {
        self.video.length = self.elementString;
    }
    //将对象添加到数组
    else if([elementName isEqualToString:@"video"])
    {
        [self.videos addObject:self.video];
    }
    
}


#pragma mark 5. 文档结束
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    for (Video * video in self.videos)
    {
         NSLog(@"%@---%@", video.name, video.length);
    }
}




#pragma mark 6. 出错处理
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"%@", parseError.localizedDescription);
}