Sax解析:
- (void)startParser{
//解析
NSString * Path = [[NSBundle mainBundle]pathForResource:@"Student" ofType:@"xml"];
//根据文件路径将文件转化为二进制
NSData *data = [NSData dataWithContentsOfFile:Path];
NSXMLParser *xml = [[NSXMLParser alloc]initWithData:data];
xml.delegate = self;
//开始解析
[xml parse];
}
2. 调用NSXMLParser的initWithData:方法,并设置代理delegate
@protocol SaxXmliParserDelegate <NSObject>
- (void)saxXmlvalueToFirstWith:(NSArray *)array;
@end
//定义协议
@property (nonatomic,assign)id<SaxXmliParserDelegate>delegate;
<p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; font-family: 'Heiti SC Light'; color: rgb(0, 132, 0);"><pre name="code" class="objc">//遵循协议
- (void)saxXmlvalueToFirstWith:(NSArray *)array{
[_tableArray addObjectsFromArray:array];
}
3.代码实现(三种必须实现方法)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:KstuArray]) {
NSMutableDictionary * stuDic = [NSMutableDictionary dictionary];
//把另外字典放在一个新的字典中
[stuDic addEntriesFromDictionary:attributeDict];
NSMutableArray *stuArr = [NSMutableArray array];
[stuDic setObject:stuArr forKey:@"array"];
[_sarray addObject:stuDic];
}
if ([elementName isEqualToString:Kstu]) {
Model * model = [[Model alloc]init];
NSMutableDictionary * lastDic = [_sarray lastObject];//放在字典中
NSMutableArray *lastArr = [lastDic objectForKey:@"array"];//放在数组中
[lastArr addObject:model];
//[model release];
}
}
//处理标签包含内容字符 (报告元素的所有或部分内容)
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
self.currentValue = string;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:kname]) {
NSMutableDictionary * dic = [_sarray lastObject];
NSMutableArray *arr = [dic objectForKey:@"array"];
Model *model = [arr lastObject];
model.name = _currentValue;
}
if ([elementName isEqualToString:kage]) {
NSMutableDictionary * dicAge = [_sarray lastObject];
NSMutableArray *arrAge = [dicAge objectForKey:@"array"];
Model *model = [arrAge lastObject];
model.age = _currentValue;
}
if ([elementName isEqualToString:ktel]) {
NSMutableDictionary * dicTel = [_sarray lastObject];
NSMutableArray *arTel = [dicTel objectForKey:@"array"];
Model *model = [arTel lastObject];
model.tel = _currentValue;
}
if ([elementName isEqualToString:Kroot]) {
NSLog(@"kroot ===== %@",_sarray);
}
[self.delegate saxXmlvalueToFirstWith:_sarray];
}