//解析:将特定数据格式(如:xml,json)中提取出来所需的内容 //SAX: Simply API for XML, xml解析的一种方式,逐行解析,读一行内容,取一行内容,速度慢,占用内存小,如果内容格式不对,不影响之前内容的读取 //iOS采取SAX解析方法一 SAX <!-- XML:Extensible Markup Language,可扩展标记语言,用于存储数据,以树的形式存储,每一个节点都有开始标签和结束标签,内容存放于开始标签和结束标签中间 --><students name = "123"]]> <student positon = "班长"]]> <name>小明</name> <sex>男</sex> <age>20</age> </student> <student> <name>小强</name> <sex>男</sex> <age>18</age> </student> <student> <name>小红</name> <sex>女</sex> <age>16</age> </student></students>@property (nonatomic, retain) NSMutableArray *studentArray;@property (nonatomic, retain) Student *student; //存放节点信息@property (nonatomic, retain) NSString *tempString;- (void)viewDidLoad { [super viewDidLoad]; // NSXMLParser, 用于解析xml 的类,使用SAX解析方式
//NSXMLParser使用步骤 //1.读取数据 //获取文件路径 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"xml"]; //1 //创建URL NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath]; //创建NSXMLParser NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url]; [url release]; //2 //创建NSData// NSData *data = [NSData dataWithContentsOfFile:filePath];// // //创建NSXMLParser// NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data]; //2.开始解析(整个的解析过程在delegate中) //设置代理 xmlParser.delegate = self; //开始解析 BOOL resutle = [xmlParser parse]; NSLog(@"%d", resutle); //解析前思考,将数据以什么形式存储(数组或字典) //对于一些固定的数据结构,一般封装成数据模型(如:Student) // Do any additional setup after loading the view.}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}#pragma mark - NSXMLParserDelegate //开始解析- (void)parserDidStartDocument:(NSXMLParser *)parser{ NSLog(@"star"); self.studentArray = [NSMutableArray arrayWithCapacity:3];} //解析出现错误- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{ NSLog(@"error:%@", parseError);} //遇到开始标签- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ //elementName:标签名字 //attributeDic:标签属性 //namespaceURI:命名空间(了解) NSLog(@"StarElentment:%@", elementName); if ([elementName isEqualToString:@"student"]) { self.student = [[Student alloc] init]; }} //开始和结束标签之间的内容- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ self.tempString = string;} //遇到结束标签- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if ([elementName isEqualToString:@"student"]) { [_studentArray addObject:_student]; [_student release]; } else if ([elementName isEqualToString:@"name"]) { self.student.name = _tempString; } else if ([elementName isEqualToString:@"sex"]) { self.student.sex = _tempString; } else if ([elementName isEqualToString:@"age"]) { self.student.age = _tempString; }} //结束解析- (void)parserDidEndDocument:(NSXMLParser *)parser{ NSLog(@"end"); NSLog(@"%@", _studentArray);}