OC中XML解析

方法

主要是5个代理方法:

  • parserDidStartDocument
  • didStartElement
  • foundCharacters
  • didEndElement
  • parserDidEndDocument
代码
#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--