#import "MyXMLParser.h"
#import "NewsModel.h"
@interface MyXMLParser ()<NSXMLParserDelegate>
/** 解析节点的数组 */
@property (nonatomic, strong)NSMutableArray *newsListArray;
/** 当前解析的对象*/
@property (nonatomic, strong)NewsModel *curModel;
/** 当前解析的字符串*/
@property (nonatomic, strong)NSString *curString;
/** 存储解析的结果*/
@property (nonatomic, strong)NSArray *dataArray;
@end
@implementation MyXMLParser
- (NSArray *)parseWithData:(NSData *)data {
//系统的XML解析类
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];//调用代理, 解决 问题。
return self.dataArray;
}
#pragma mark - NSXMLParser代理
//节点开始的方法
- (void)parser:(NSXMLParser *)parser didStartElement:(nonnull NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(nonnull NSDictionary<NSString *,NSString *> *)attributeDict{
//elementName是节点的名字
if ([elementName isEqualToString:@"newslist"]) {
//创建数组
//newslist 开始
// √
self.newsListArray = [NSMutableArray array];
}else if ([elementName isEqualToString:@"news"]){
//创建一个对象
//news 开始
// †
self.curModel = [[NewsModel alloc] init]; // NewsModel
}
}
//找到字符串的方法
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
self.curString = string;
//
}
//节点结束的方法
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"newslist"]) {
// Array<NewsModel>
// -ed
//newslist 结束
// √
self.dataArray = self.newsListArray;
self.newsListArray = nil;
}else if ([elementName isEqualToString:@"news"]) {
// Array<NewsModel>
// -ing
//news 结束
// †
[self.newsListArray addObject:self.curModel];
self.curModel = nil;
}else{
//给对象的属性赋值
//NewsModel
// - ing
//
if (![elementName isEqualToString:@"newstype"]) {
NSString *key = elementName;
if ([key isEqualToString:@"id"]) {
key = @"newsId";
}
//使用KVC赋值
[self.curModel setValue:self.curString forKey:key];
}
}
}
@end
附: Model
Ø
#import <Foundation/Foundation.h>
@class NewsTypeModel;
@interface NewsModel : NSObject
@property (nonatomic, strong)NSString *newsId;
@property (nonatomic, strong)NSString *title;
@property (nonatomic, strong)NSString *body;
@property (nonatomic, strong)NSString *commentCount;
@property (nonatomic, strong)NSString *author;
@property (nonatomic, strong)NSString *authorid;
@property (nonatomic, strong)NSString *pubDate;
@property (nonatomic, strong)NSString *url;
@property (nonatomic, strong)NewsTypeModel *newstype;
@end
@class GDataXMLElement;
@interface NewsTypeModel : NSObject
@property (nonatomic, strong)NSString *type;
@property (nonatomic, strong)NSString *authoruid2;
@property (nonatomic, strong)NSString *eventurl;
@end