XCode自带解析SAX解析

Posted 恒远也

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XCode自带解析SAX解析相关的知识,希望对你有一定的参考价值。

 1 #import "XMLViewController.h"
 2 #import "Student.h"
 3 @interface XMLViewController ()<NSXMLParserDelegate>
 4 @property (strong,nonatomic) NSMutableArray *stuArray;
 5 @property (strong,nonatomic) Student *student;
 6 @property (strong,nonatomic) NSString *value;
 7 @end
 8 
 9 @implementation XMLViewController
10 
11 - (void)viewDidLoad {
12     [super viewDidLoad];
13     // Do any additional setup after loading the view.
14 }
15 - (IBAction)didClickParserButtonAction:(UIButton *)sender {
16     NSData *xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XML_stu" ofType:@"txt"]];
17     //创建SAX解析工具NSXMLParser
18     NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
19     //设置代理
20     xmlParser.delegate = self;
21     //开始解析
22     [xmlParser parse];
23 }
24 //开始解析 XML 文档
25 -(void)parserDidStartDocument:(NSXMLParser *)parser
26 {
27     NSLog(@"开始文档");
28     //初始化数组
29     self.stuArray = [NSMutableArray new];
30 }
31 
32 //找到一个节点(找到一个开始标签)
33 -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
34 {
35     NSLog(@"开始标签");
36     if ([elementName isEqualToString:@"student"]) {
37        self.student = [[Student alloc] init];
38         
39     }
40 }
41 
42 //获得标签内容
43 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
44 {
45     NSLog(@"获取内容:%@",string);
46     self.value = string;
47 }
48 
49 
50 //找到一个结束标签
51 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
52 {
53     NSLog(@"结束标签");
54     //KVC 赋值
55     [self.student setValue:self.value forKey:elementName];
56     
57     //若student标签结束,添加到数组
58     if ([elementName isEqualToString:@"student"]) {
59         [self.stuArray addObject:self.student];
60     }
61 }
62 //结束解析XML文档
63 -(void)parserDidEndDocument:(NSXMLParser *)parser
64 {
65     NSLog(@"结束文档");
66     NSLog(@"%@",self.stuArray);
67 }
68 //解析出错
69 -(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
70 {
71     NSLog(@"解析出错:%@",parseError);
72 }
73 
74 - (void)didReceiveMemoryWarning {
75     [super didReceiveMemoryWarning];
76     // Dispose of any resources that can be recreated.
77 }
78 
79 
80 
81 @end

 

以上是关于XCode自带解析SAX解析的主要内容,如果未能解决你的问题,请参考以下文章

从流输入中解析没有根元素的 XML 片段列表

在BlackBerry中使用SAX解析器解析XML

XML解析

XML解析之SAX解析技术案例

Java自带的XML解析器接口

Sax 解析 XMl