1) 读取文件路径
NSString *path = [NSBundle mainBundle] pathForResource:@“Student” ofType@“txt”]];
2)读取数据
NSData *data = [NSData dataWithContentOfFile:path];
1> 开始XML sax解析, 需要遵循NSXMLParserDelegate
NSXMLParser *firstParser = [NSXMLParser alloc]initWithData:data];
2> 指定代理人
firstParser.delegate = self;
3> 开始解析
[firstParser parse];
4> 开始解析数据
-(void)parserDidStartDocument:(NSXMLParser *)parser
{ self.DataArray = [NSMutableArray array]; }
5> 开始读取节点
-(void)parser:(NSXMLParser *)parser didStarElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifieName:(NSString *)qName attributes:(NSDictionary *)attributeDic
{ if([elementName isEqualToString:@“stu”]){
Student *stu = [Student alloc] init];
[self.DataArray addObject:stu];
} self.currentElement = elementName;
}
6> 读取节点内容
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
Student *student = [self.DataArray lastObject];
[student setValue:string forKey:self.currentElement];
}
7> 当前节点读取结束
-(void)parser:(NSXMLParser *)parser didEndElement:(MSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
self.currentElement = nil;
}
8> 当前文档读取结束
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(@“当前文档读取结束”);
}