前端之家收集整理的这篇文章主要介绍了
SAX for XML,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#import "ViewController.h"
#import "VideoModel.h"
@interface ViewController () <NSXMLParserDelegate>
@end
@implementation ViewController {
NSMutableArray *_videoM;
NSMutableString *_stringM;
VideoModel *_currentModel;
}
- (void)viewDidLoad {
[super viewDidLoad];
_videoM = [NSMutableArray array];
_stringM = [NSMutableString string];
[self loadData];
}
- (void)loadData
{
NSURL *URL = [NSURL URLWithString:@"http://localhost/videos.xml"];
[[[NSURLSession sharedSession] dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response,NSError * _Nullable error) {
if (error == nil && data != nil) {
NSXMLParser *XMLParser = [[NSXMLParser alloc] initWithData:data];
NSXMLParser *xmlparser = [[NSXMLParser alloc]initWithData:data];
XMLParser.delegate = self;
[XMLParser parse];
} else {
NSLog(@"%@",error);
}
}] resume];
}
#pragma mark - NSXMLParserDelegate
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(@"1.开始解析XML文档");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
{
if ([elementName isEqualToString:@"video"]) {
_currentModel = [[VideoModel alloc] init];
_currentModel.videoId = attributeDict[@"videoId"];
[_videoM addObject:_currentModel];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[_stringM appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName
{
if ([elementName isEqualToString:@"videos"] || [elementName isEqualToString:@"video"]) {
return;
}
[_currentModel setValue:_stringM forKey:elementName];
[_stringM setString:@""];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"5.结束解析XML文档");
NSLog(@"%@",_videoM);
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(@"6.监听解析是否出错 = %@",parseError);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
原文链接:https://www.f2er.com/xml/294786.html