SAX解析
SAX:Simple API for XML。基于事件驱动的解析⽅方式,逐⾏行解析 数据。(采⽤用协议回调机制)
NSXMLParser类
NSXMLParser是iOS⾃自带的XML解析类。采⽤用SAX⽅方式解析数据。
解析过程由NSXMLParserDelegate协议⽅方法回调
解析过程:开始标签->取值->结束标签->取值
<?xml version = "1.0" encoding = "UTF-8"?>
<students>
<student>
<name>yadong</name>
<sex>man</sex>
<phone>18310057255</phone>
</student>
<student>
<name>kelin</name>
<sex>man</sex>
<phone>18410057255</phone>
</student>
<student>
<name>marry</name>
<sex>woman</sex>
<phone>18510057255</phone>
</student>
</students>
#import "ViewController.h"
#import "StudentModal.h"
@interface ViewController () <NSXMLParserDelegate>
{
// 用来记录当前正在操作的标签
NSString *_currentElement;
}
@property (nonatomic,strong) NSMutableArray *xmlSAXArray;
@end
- (IBAction)XMLSAXBtttonDidClicked:(UIButton *)sender {
// 1、拿到 xml 文件的路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"xml"];
// 2、根据文件路径获取文件的内容
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
// 3、根据 data 初始化一个 NSXMLParser 对象
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
// 4、设置 NSXMLParser 对象的相关属性
// 是否处理命名空间
[parser setShouldProcessNamespaces:NO];
// 是否设置报告处理(前缀)
[parser setShouldReportNamespacePrefixes:NO];
// 5、设置代理
parser.delegate = self;
// 6、开始解析(调用)
[parser parse];
}
实现 NSXMLParser 代理方法
开始解析(打开文档)
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
// 初始化数组
self.xmlSAXArray = [NSMutableArray array];
NSLog(@"打开文档");
}
打开标签
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"student"]) {
StudentModal *modal = [[StudentModal alloc] init];
[self.xmlSAXArray addObject:modal];
}
_currentElement = elementName;
NSLog(@"打开标签%@",elementName);
}
取值
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
StudentModal *modal = [self.xmlSAXArray lastObject];
if ([_currentElement isEqualToString:@"name"]) {
modal.name = string;
} else if ([_currentElement isEqualToString:@"sex"]) {
modal.sex = string;
} else if ([_currentElement isEqualToString:@"phone"]) {
modal.phoneNumber = string;
}
NSLog(@"取值%@",string);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { _currentElement = nil; NSLog(@"关闭标签%@",elementName); }
关闭文档
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
// 打印验证
for (StudentModal *stu in self.xmlSAXArray) {
NSLog(@"%@,%@,%@",stu.name,stu.sex,stu.phoneNumber);
}
NSLog(@"关闭文档");
}