使用步骤
// 传入XML数据,创建解析器
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
// 设置代理,监听解析过程
parser.delegate = self;
// 开始解析
[parser parse];
NSXMLParser采取的是SAX方式解析,特点是事件驱动,下面情况都会通知代理
当扫描到文档(Document)的开始与结束
当扫描到元素(Element)的开始与结束
NSXMLParserDelegate
@protocol NSXMLParserDelegate <NSObject>
@optional
- (void)parserDidStartDocument:(NSXMLParser *)parser; // sent when the parser begins parsing of the document.当扫描到文档的开始时调用(开始解析)
- (void)parserDidEndDocument:(NSXMLParser *)parser; // sent when the parser has completed parsing. If this is encountered, the parse was successful.当扫描到文档的结束时调用(解析完毕)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict;
//当扫描到元素的开始时调用(attributeDict存放着元素的属性)
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName; // sent when an end tag is encountered. The various parameters are supplied as above.当扫描到元素的结束时调用
@end
原生API解析XML
- (void) parserDatabyNSXMLParser:(NSData*)data{
// 传入XML数据,创建解析器
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
// 设置代理,监听解析过程
parser.delegate = self;
NSLog(@"-----begin%s",__func__);
// 开始解析
[parser parse];//Starts the event-driven parsing operation.
}
#pragma mark - NSXMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{
// NSLog(@"%s---elementName:%@------namespaceURI:%@--qualifiedName%@----attributeDict:%@",__func__,elementName,namespaceURI,qName,attributeDict);
if ([elementName isEqualToString:@"videos"]) {
return;
}else if ([elementName isEqualToString:@"video"]){
[self.videos addObject:[HSVideoModel videoWithDictionary:attributeDict]];
}
}
作者:u011018979 发表于2017/7/10 9:34:40 原文链接
阅读:127 评论:0 查看评论