XML解析之转模型
准备模型类
.h文件中的声明
@interface VideoModel : NSObject
/// 视频编号
@property (nonatomic,copy) NSString *videoId;
/// 视频名称
@property (nonatomic,copy) NSString *name;
/// 视频长度
@property (nonatomic,copy) NSString *length;
/// 视频链接
@property (nonatomic,copy) NSString *videoURL;
/// 视频图标
@property (nonatomic,copy) NSString *imageURL;
/// 视频标题
@property (nonatomic,copy) NSString *desc;
/// 视频作者
@property (nonatomic,copy) NSString *teacher;
/// 字典转模型 : 解析XML的时候,没有字典,所以这个不需要
//+ (instancetype)videoWithDict:(NSDictionary *)dict;
@end
/*
01.C语言-语法预览
320
/itcast/videos/01.C语言-语法预览.mp4
/itcast/images/head1.png
C语言-语法预览
李雷
*/
.m文件中的实现
@implementation VideoModel
/// 无用处
+ (instancetype)videoWithDict:(NSDictionary *)dict
{
// 创建模型对象
VideoModel *v = [[VideoModel alloc] init];
// KVC 字典转模型
[v setValuesForKeysWithDictionary:dict];
// 返回模型对象
return v;
}
/// 打印模型的详细内容
- (NSString *)description
{
return [NSString stringWithFormat:@”<%@ : %p> { videoId : %@, name : %@, length : %@, videoURL : %@, imageURL : %@, desc : %@, teacher : %@}”, [self class], self, self.videoId, self.name, self.length, self.videoURL, self.imageURL, self.desc, self.teacher];
}
@end
解析XML文件
将XML文件中的数据读取出来,转换成可以直接使用的模型数据.
XML数据转模型数据的准备工作
@interface ViewController ()
/// video对应的模型对象
@property (nonatomic,strong) VideoModel *currentVideo;
/// 拼接节点之间内容的字符串
@property (nonatomic,copy) NSMutableString *stringM;
/// 模型数组
@property (nonatomic,strong) NSMutableArray *videoM;
@end
@implementation ViewController
(NSMutableString *)stringM
{
if (_stringM == nil) {
_stringM = [NSMutableString string];
}
return _stringM;
}
(NSMutableArray *)videoM
{
if (_videoM == nil) {
_videoM = [NSMutableArray array];
}
return _videoM;
}
实现代理方法
1.开始解析文档
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(@”1.开始解析文档 %@”,[NSThread currentThread]);
}
2.找开始节点
- (void)parser:(NSXMLParser )parser didStartElement:(NSString )elementName namespaceURI:(NSString )namespaceURI qualifiedName:(NSString )qName attributes:(NSDictionary