SAX解析

#import "ViewController.h"

#import "Student.h"

//一共要3步.第一引入libxml2.tbd//2.-fno-objc-arc//3./usr/include/libxml2

@interface ViewController ()

@property(nonatomic,strong)NSString *currentlement;//存放当前节点

@property(nonatomic,strong)NSMutableArray *array;//存放解析出来的模型

@end

@implementation ViewController

-(NSMutableArray *)array{

if (!_array) {

_array = [NSMutableArray array];

}return _array;

}

- (void)viewDidLoad {

[super viewDidLoad];

NSLog(@"SAX解析");

//1.获取文件路径

NSString *filepath = [[NSBundle mainBundle]pathForResource:@"XML_stu" ofType:@"txt"];

//2.创建data

NSData *data = [NSData dataWithContentsOfFile:filepath];

//3.创建解析对象

NSXMLParser *parser =[[NSXMLParser alloc]initWithData:data];

//4.遵循协议设置代理

parser.delegate = self;

//5.开始解析

[parser parse];

}

//实现协议方法

//1.开始解析

-(void)parserDidStartDocument:(NSXMLParser *)parser{

NSLog(@"开始解析");

}

//2.开始解析标签-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*)attributeDict{

//获取当前节点

NSLog(@"%@",elementName);

self.currentlement =elementName;

//这一步的作用是根据节点提供的数据,来创建对应的modle(没有复制过程,只是创建模型)

if ([elementName isEqualToString:@"student"]) {

//初始化一个学生对象

Student *stu =[[Student alloc]init];

[self.array addObject:stu];

}

//3.读取标签的值

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

NSLog(@"%@",string);

//我们需要数组里面最后一个值

Student *stu =self.array.lastObject;

//使用KVC编码赋值

[stu setValue:string forKey:self.currentlement];

}

//4.结束标签解析

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

NSLog(@"%@",elementName);

self.currentlement =nil;

}

//5.结束文档解析

-(void)parserDidEndDocument:(NSXMLParser *)parser{

NSLog(@"文档解析结束");

for (Student *stu in self.array) {

NSLog(@"%@",stu);

}

}

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

你可能感兴趣的:(SAX解析)