<?xml version = "1.0" encoding = "UTF8" standalone = "yes" ?>
<!--上面的是预处理指令 编码方式为UTF8 版本为1.0 standalone 说明他是独立的 与其他没有关系-->
<!--以下是一个学生名单-->
<student_list>
<student>
<stu_name>otis</stu_name>
<stu_class>T23</stu_class>
<stu_num>2003081205</stu_num>
</student>
<stu_name>tim</stu_name>
<stu_num>2003081210</stu_num>
<stu_name>lili</stu_name>
<stu_class>T24</stu_class>
<stu_num>2003081206</stu_num>
</student_list>
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSXMLParserDelegate>
@property (strong,nonatomic)IBOutlet UITextView *m_pTextViewResult;
)NSXMLParser *m_pXmlParse;//系统带得 解析的类 即:解析器
)NSMutableString *m_pStrSaxResult;//存解析结果
)NSMutableString *m_pStrSaxTmp;//存解析的临时结果
-(IBAction)btnClickXMLParSEOfSAX:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view,typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//按钮关联方法 开始解析
-(IBAction)btnClickXMLParSEOfSAX:(id)sender
{
NSLog(@"%s",__func__);
//*******加载文件
//获取text 路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"text" ofType:@"xml"];
//定义一个文件句柄关联路径
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];//读取
//读取数据到data
NSData *data = [file readDataToEndOfFile];
[file closeFile];
//根据xml数据进行创建解析器 初始化 .m_pXmlParse
self.m_pXmlParse = [[NSXMLParser alloc]initWithData:data];
//设定代理
[self.m_pXmlParse setDelegate:self];//解析器与当前视图建立委托
self.m_pStrSaxResult = [[NSMutableString alloc]init];
self.m_pStrSaxTmp = [[NSMutableString alloc]init];
//通知解析器开始解析,返回一个bool值,标志解析成功或失败
BOOL flag = [self.m_pXmlParse parse];
if (flag) {
[_m_pStrSaxResult appendFormat:@"%@\r\n",@"获取指定路径的 xml 文件成功"];
}
else
{
}
}
//开始解析
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(@"%s",__func__);
[_m_pStrSaxResult appendFormat:@"%@\r\n",@"开始解析 xml of SAX 文件"];
];
}
//遇到数据时回调,包括空格和回车
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"%s",__func__);
[_m_pStrSaxTmp setString:@""];
[_m_pStrSaxTmp appendFormat:@"%@",string];
NSLog(@"string = %@",string);
}
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName //之处理 end 标签
namespaceURI:(NSString *)namespaceURL
qualifiedName:(NSString *)qName
{
NSLog(@"%s",__func__);
if (NSOrderedSame == [elementName compare:@"student"]) {
[_m_pStrSaxResult appendFormat:@"%@\n",@"*******student*********"];
}
else if (NSOrderedSame == [elementName compare:@"student_list"])
{
}
else
{
[_m_pStrSaxResult appendFormat:@"%@ = %@\r\n",elementName,_m_pStrSaxTmp];
}
}
//完成解析xml 文档
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"%s",__func__);
[_m_pStrSaxResult appendFormat:@"%@",@"解析 xml 文件完成"];
[_m_pTextViewResult setText:_m_pStrSaxResult];
}
@end