XML parsing for iOS network development tutorials and xml parsing for ios tutorials

Source: Internet
Author: User
Tags xml example

XML parsing for iOS network development tutorials and xml parsing for ios tutorials

XML Introduction

What is XML?

ExtensibleMarkupLanguage. extensible markup language.

Like JSON, it is also a common data format for interaction.

It is also called XML Document)

XML example
 
  
   
    

    
   
  
 
XML Syntax:

A common XML document generally consists of the following parts:

Document declaration

Element)

An element includes the content of the start tag and end tag: <video> porn </video> elements with no content: <video> & nbsp; </video> short for elements without content: <video> a single element can be nested with several child elements (Cross Nesting is not allowed) <videos> <video> <name> Part 1 </name> <length> 30 </length> </video> </videos>: the maximum number of XML documents in a standard is 1. root elements, other elements are child elements of the root element </video>

Attribute)

<Video length = "30" name = "Porn 01st"> the video element has two attribute values: name and length, which must be enclosed in double quotation marks & quot; or single quotation marks & #39; & #39; in fact, the information represented by attributes can also be represented by sub-elements, for example, <video> <name> Division 3, 01st </name> <length> 30 </length> </video>
  XML Parsing

There are two ways to parse XML

DOM: load the entire XML file into the memory at a time, which is more suitable Parse small filesSAX: Starting from the root element, it is suitable for parsing one element and one element in sequence. Parse large files

SAX parsing: (NSXMLParser)

# Import "ViewController. h" # import "UIImageView + WebCache. h" # import
 
  
# Import "ZYVideo. h" # import "MJExtension. h" # define baseUrlStr @ "https: // 120.25.226.186: 32812" @ interface ViewController ()
  
   
/* Storage model array */@ property (nonatomic, strong) NSMutableArray * videos; @ end @ implementation ViewController-(NSMutableArray *) videos {if (! _ Videos) {_ videos = [NSMutableArray array];} return _ videos;}-(void) viewDidLoad {[super viewDidLoad]; // replace the name of the attribute in the model with the system keyword. (system-provided method conflict) [ZYVideo mj_setupReplacedKeyFromPropertyName: ^ NSDictionary * {return @ {@ "ID": @ "id" };}]; // 1. url NSURL * url = [NSURL URLWithString: @ "https: // localhost: 8080/MJServer/video? Method = get & type = XML "]; // 2. create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. create asynchronous connection [NSURLConnection failed: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// fault tolerance Processing if (connectionError) {return;} // 4. parse data (deserialization) NSXMLParser * parser = [[NSXMLParser alloc] initWithData: data]; parser. delegate = self; // start parsing: The parse method is blocked. reloadData [parser parse] is called only after the parsing is complete; // 5. refresh the UI [self. tableView reloadData] ;}] ;}# pragma-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
   
    
*) AttributeDict {// NSLog (@ "% @ --- % @", elementName, attributeDict); // SAX resolution, if ([elementName isinclutostring: @ "videos"]) {return;} // dictionary to model [self. videos addObject: [ZYVideo failed: attributeDict];} // an element is 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 ----") ;}# pragma-mark tableView data source method-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. videos. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {// 1. set the reuse identifier static NSString * ID = @ "video"; // 2. reuse cell in the cache pool (automatically created if not) UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: ID]; // 3. set Data // NSDictionary * dict = self. videos [indexPath. row]; ZYVideo * video = self. videos [indexPath. row]; cell. textLabel. text = video. name; cell. detailTextLabel. text = [NSString stringWithFormat: @ "playback time: % @", video. length]; // use SDWebImage to set the url of the image downloaded from the network // splice the image // NSString * baseUrlStr = @ "https: // 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 Data // NSDictionary * dict = self. videos [indexPath. row]; ZYVideo * video = self. videos [indexPath. row]; // 2. splicing resource path NSString * urlStr = [baseUrlStr stringByAppendingPathComponent: video. url]; // 3. create a player MPMoviePlayerViewController * mpc = [[MPMoviePlayerViewController alloc] initWithContentURL: [NSURL URLWithString: urlStr]; // 4. the Controller [self presentViewController: nmanimated: YES completion: nil];} @ end is displayed.
   
  
 

DOM parsing :(GDataXMLDocument)

Configuration before using DOM parsing:

1. Import the GDataXML file.

# Import "ViewController. h" # import "UIImageView + WebCache. h" # import
 
  
# Import "ZYVideo. h "# import" MJExtension. h "# import" GDataXMLNode. h "# define baseUrlStr @" https: // 120.25.226.186: 32812 "@ interface ViewController ()/* storage model array */@ property (nonatomic, strong) NSMutableArray * videos; @ end @ implementation ViewController-(NSMutableArray *) videos {if (! _ Videos) {_ videos = [NSMutableArray array];} return _ videos;}-(void) viewDidLoad {[super viewDidLoad]; // replace the name of the attribute in the model with the system keyword. (system-provided method conflict) [ZYVideo mj_setupReplacedKeyFromPropertyName: ^ NSDictionary * {return @ {@ "ID": @ "id" };}]; // 1. url NSURL * url = [NSURL URLWithString: @ "https: // localhost: 8080/MJServer/video? Method = get & type = XML "]; // 2. create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. create asynchronous connection [NSURLConnection failed: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// fault tolerance Processing if (connectionError) {return;} // 4. parse data (deserialization) // 4.1 load the entire XML document GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithData: data options: kNilOptions error: nil]; // 4.2 root element of the XML document. get all the child elements whose names are video in the root element NSArray * eles = [doc. rootElement elementsForName: @ "video"]; // 4.3 traversal operation for (GDataXMLElement * ele in eles) {// get the attributes in the child element ---> 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 the UI [self. tableView reloadData] ;}] ;}# pragma-mark tableView data source method-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. videos. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {// 1. set the reuse identifier static NSString * ID = @ "video"; // 2. reuse cell in the cache pool (automatically created if not) UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: ID]; // 3. set Data // NSDictionary * dict = self. videos [indexPath. row]; ZYVideo * video = self. videos [indexPath. row]; cell. textLabel. text = video. name; cell. detailTextLabel. text = [NSString stringWithFormat: @ "playback time: % @", video. length]; // use SDWebImage to set the url of the image downloaded from the network // splice the image // NSString * baseUrlStr = @ "https: // 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 Data // NSDictionary * dict = self. videos [indexPath. row]; ZYVideo * video = self. videos [indexPath. row]; // 2. splicing resource path NSString * urlStr = [baseUrlStr stringByAppendingPathComponent: video. url]; // 3. create a player MPMoviePlayerViewController * mpc = [[MPMoviePlayerViewController alloc] initWithContentURL: [NSURL URLWithString: urlStr]; // 4. the Controller [self presentViewController: nmanimated: YES completion: nil];} @ end is displayed.
 

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.