OC中XML解析

方法

主要是5个代理方法:

  • parserDidStartDocument
  • didStartElement
  • foundCharacters
  • didEndElement
  • parserDidEndDocument

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#import "ViewController.h"
#import "GameListModel.h"
#import <objc/runtime.h>

@interface ViewController ()<NSXMLParserDelegate>
@property (nonatomic) GameListModel *gameList;

//临时变量
@property (nonatomic) NSMutableArray *dataArr;
@property (nonatomic) GameListDataModel *dataModel;
@property (nonatomic) NSString *currentDocument;
@end

@implementation ViewController

#pragma -mark 生命周期
- (void)viewDidLoad {
[super viewDidLoad];
// NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"Games" ofType:@"xml"];
NSURL *xmlURL = [[NSBundle mainBundle] URLForResource:@"Games" withExtension:@"xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
parser.delegate = self;
[parser parse];
NSLog(@"error:%@",_gameList.error);
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList([GameListDataModel class], &count);
for (GameListDataModel *model in _gameList.dataList) {
for (int i = 0; i < count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSLog(@"%@:%@",[NSString stringWithUTF8String:propertyName],[model valueForKey:[NSString stringWithUTF8String:propertyName]]);
}
NSLog(@"************");
}
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma -mark NSXMLParserDelegate

//开始读xml文件
- (void)parserDidStartDocument:(NSXMLParser *)parser {
_gameList = [GameListModel new];
_dataArr = [NSMutableArray new];
}

//读取某个标签
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
_currentDocument = elementName;
if ([elementName isEqualToString:@"data"]) {
_dataModel = [GameListDataModel new];
}
}

//读取标签中的内容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(_dataModel) {
[_dataModel setValue:string forKey:_currentDocument];
} else if ([_currentDocument isEqualToString:@"error"]) {
_gameList.error = string;
}
}

//结束某个标签的读取
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"data"]) {
[_dataArr addObject:_dataModel];
_dataModel = nil;
}
_currentDocument = nil;
}

//xml读取结束
- (void)parserDidEndDocument:(NSXMLParser *)parser {
_gameList.dataList = [_dataArr copy];
}

@end

源码 (提取码:f5f9)

长时间不学习新的东西就会很焦虑…学到新的东西心里就会很踏实…

–EOF–