XML introduction
What is XML?
The full name is Extensible Markup Language. Extensible Markup Language.
Like JSON, it is also a commonly used data format for interaction.
Usually also known as XML Document
XML Give an example <videos> <video name="Xiaohuang People Part 01" length="30" /> <video name="Xiaohuang People Part 02" length="19" /> <video name="Xiaohuang People Part 03" length="33" /> </videos>
A common XML document generally consists of the following parts
Document declaration
Element s
An element includes the start tag and the end tag Elements with content: < video > Xiaohuang people </video > Elements without content: <video></video> Element abbreviation without content: <video/> An element can nest several sub-elements (no cross-nesting can occur) <videos> <video> < name > Part 01 of Xiaohuang People </name > <length>30</length> </video> </videos> A canonical XML document has at most one root element, and all other elements are descendants of the root element.
Attribute
An element can have multiple attributes <video name="Part 01 of the Little Yellow Man" length="30"/> The video element has name and length attributes Attribute values must be enclosed in double or single quotation marks In fact, information represented by attributes can also be represented by sub-elements, such as <video> < name > Part 01 of Xiaohuang People </name > <length>30</length> </video>
XML parsing
There are two ways to parse XML
- DOM: Loading the entire XML document into memory at one time is more suitable for parsing small files.
- SAX: Starting from the root element, one element in sequence is parsed down, which is more suitable for parsing large files.
SAX parsing: (NSXML Parser)
#import "ViewController.h" #import "UIImageView+WebCache.h" #import <MediaPlayer/MediaPlayer.h> #import "ZYVideo.h" #import "MJExtension.h" #define baseUrlStr @"http://120.25.226.186:32812" @interface ViewController ()<NSXMLParserDelegate> /* An array of storage models */ @property (nonatomic, strong) NSMutableArray *videos; @end @implementation ViewController - (NSMutableArray *)videos { if (!_videos) { _videos = [NSMutableArray array]; } return _videos; } - (void)viewDidLoad { [super viewDidLoad]; // The name of the attribute in the replacement model conflicts with the system keyword. [ZYVideo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{ return @{ @"ID" : @"id" }; }]; //1. determine url NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video?method=get&type=XML"]; //2. Create requests NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3. Create asynchronous connections [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { // fault tolerant if (connectionError) { return ; } // 4. Parsing data (deserialization) NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; parser.delegate = self; // Start parsing: The parse method is blocked and reloadData will only be called after parsing. [parser parse]; //5. refresh UI [self.tableView reloadData]; }]; } #Pagma-mark NSXMLParser proxy method // Start parsing - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"Start parsing----"); } // Start parsing an element - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict { // NSLog(@"%@---%@",elementName,attributeDict); // SAX parsing, one node parsing if ([elementName isEqualToString:@"videos"]) { return; } // Dictionary Conversion Model [self.videos addObject:[ZYVideo mj_objectWithKeyValues:attributeDict]]; } // An element has been parsed. - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSLog(@"%@",elementName); } // End resolution - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"End resolution----"); } #Data Source Method of pragma-mark tableView - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.videos.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //1. Setting Reuse Identity static NSString *ID = @"video"; //2. Reuse cells in the cache pool (if not automatically created) UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; //3. Setting up data // NSDictionary *dict = self.videos[indexPath.row]; ZYVideo *video = self.videos[indexPath.row]; cell.textLabel.text = video.name; cell.detailTextLabel.text = [NSString stringWithFormat:@"Play time:%@",video.length]; // Setting up images downloaded from the network using SDWebImage // url of mosaic picture // NSString *baseUrlStr = @"http://120.25.226.186:32812"; NSString *urlStr = [baseUrlStr stringByAppendingPathComponent:video.image]; [cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"qq"]]; // NSLog(@"----%@",video.ID); return cell; } #Proxy Method of pragma-mark tableView - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //1. Get the data // NSDictionary *dict = self.videos[indexPath.row]; ZYVideo *video = self.videos[indexPath.row]; //2. Splicing resource paths NSString *urlStr = [baseUrlStr stringByAppendingPathComponent:video.url]; //3. Create Players MPMoviePlayerViewController *mpc = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:urlStr]]; //4. Pop-up Controller [self presentViewController:mpc animated:YES completion:nil]; } @end
DOM parsing: (GDataXML Document)
Configuration before parsing using DOM:
1. Import GData XML file.
#import "ViewController.h" #import "UIImageView+WebCache.h" #import <MediaPlayer/MediaPlayer.h> #import "ZYVideo.h" #import "MJExtension.h" #import "GDataXMLNode.h" #define baseUrlStr @"http://120.25.226.186:32812" @interface ViewController () /* An array of storage models */ @property (nonatomic, strong) NSMutableArray *videos; @end @implementation ViewController - (NSMutableArray *)videos { if (!_videos) { _videos = [NSMutableArray array]; } return _videos; } - (void)viewDidLoad { [super viewDidLoad]; // The name of the attribute in the replacement model conflicts with the system keyword. [ZYVideo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{ return @{ @"ID" : @"id" }; }]; //1. determine url NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video?method=get&type=XML"]; //2. Create requests NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3. Create asynchronous connections [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { // fault tolerant if (connectionError) { return ; } // 4. Parsing data (deserialization) // 4.1 Load the entire XML document GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:kNilOptions error:nil]; //4.2 The root element of an XML document. Get all descendant elements named video s inside the root element NSArray *eles = [doc.rootElement elementsForName:@"video"]; //4.3 traversal operation for (GDataXMLElement *ele in eles) { // Get the attributes in the child elements - > model - > add to self.videos ZYVideo *video = [[ZYVideo alloc] init]; video.name = [ele attributeForName:@"name"].stringValue; video.length = [ele attributeForName:@"length"].stringValue; video.image = [ele attributeForName:@"image"].stringValue; video.ID = [ele attributeForName:@"id"].stringValue; video.url = [ele attributeForName:@"url"].stringValue; [self.videos addObject:video]; } //5. refresh UI [self.tableView reloadData]; }]; } #Data Source Method of pragma-mark tableView - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.videos.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //1. Setting Reuse Identity static NSString *ID = @"video"; //2. Reuse cells in the cache pool (if not automatically created) UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; //3. Setting up data // NSDictionary *dict = self.videos[indexPath.row]; ZYVideo *video = self.videos[indexPath.row]; cell.textLabel.text = video.name; cell.detailTextLabel.text = [NSString stringWithFormat:@"Play time:%@",video.length]; // Setting up images downloaded from the network using SDWebImage // url of mosaic picture // NSString *baseUrlStr = @"http://120.25.226.186:32812"; NSString *urlStr = [baseUrlStr stringByAppendingPathComponent:video.image]; [cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"qq"]]; // NSLog(@"----%@",video.ID); return cell; } #Proxy Method of pragma-mark tableView - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //1. Get the data // NSDictionary *dict = self.videos[indexPath.row]; ZYVideo *video = self.videos[indexPath.row]; //2. Splicing resource paths NSString *urlStr = [baseUrlStr stringByAppendingPathComponent:video.url]; //3. Create Players MPMoviePlayerViewController *mpc = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:urlStr]]; //4. Pop-up Controller [self presentViewController:mpc animated:YES completion:nil]; } @end