iOS elearning------8 request processing of XML format data in code block encapsulation

Source: Internet
Author: User

#pragma mark load xml-(void) loadxml{//Get network data.    NSLog (@ "load xml");  Load data from the Web server nsstring *str = @ "Http://www.baidu.com?format=xml";    Here is the Scribble//1 cv nsurl nsurl *url = [Nsurl urlwithstring:str]; 2 Establish nsurlrequest nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:    Nsurlrequestuseprotocolcachepolicy timeoutinterval:2.0f];    3 Establish Nsurlconnect synchronization method to load data nsurlresponse *response = nil;            Nserror *error = nil; Synchronous load Data NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&    ERROR];        Myxmlparser *myparser = [[Myxmlparser alloc]init];    Lazy Loading instantiated data if (self.datalist = = nil) {self.datalist = [Nsmutablearray array];    }else{[Self.datalist removeallobjects]; }//Parse data [Myparser xmlparserwithdata:data startname:@ "video" startelement:^ (        Nsdictionary *dict) {//1 instantiation Currentvideo self.currentvideo = [[Video alloc]init];  2 Setting VideoID      Self.currentVideo.videoId = [dict[@ "VideoID"]integervalue]; } endelement:^ (NSString *elementname, NSString *result) {if ([elementname isequaltostring:@ "name"]) {s        Elf.currentVideo.name = result;        }else if ([elementname isequaltostring:@ "Length"]) {self.currentVideo.length = [result IntegerValue];        }else if ([elementname isequaltostring:@ "Videourl"]) {self.currentVideo.videoId = [result IntegerValue];        }else if ([elementname isequaltostring:@ "ImageURL"]) {Self.currentVideo.imageURL = result;        }else if ([elementname isequaltostring:@ "desc"]) {Self.currentVideo.desc = result;        }else if ([elementname isequaltostring:@ "Teacher"]) {self.currentVideo.teacher = result;        }else if ([ElementName isequaltostring:@ "video"]) {[Self.datalist addObject:self.currentVideo];        }} finishedparser:^{Self.currentvideo = nil;   [Self.tableview Reloaddata]; //Refresh table Data} errorparser:^{NSLog (@ "Parse error");        Emptying temporary data Self.currentvideo = nil;    Empty array [self.datalist removeallobjects]; }];}
<pre name= "code" class= "OBJC" > #import <foundation/foundation.h>//Proxy methods need to interact with callers://2 interactive elements: elementname  attributedict//4 interactive elements: elementname brokered strings//5 notifications only  //6 only//define block code: typedef void (^startelementblock) ( Nsdictionary *dict); typedef void (^endelementblock) (NSString *elementname, NSString *result); typedef void (^ Xmlparsernotificationblock) (); @interface myxmlparser:nsobject//Definition parsing method/*  node name starting with the data XML startname Startelement Start Node method endElement  End Node method finishedparser document parsing ends. Errorparse  Document parsing error. */-(void) Xmlparserwithdata: (NSData *) Data                 startname: (NSString *) StartName                 startelement: ( Startelementblock) startelement                 endElement: (endelementblock) endElement                 finishedparser: ( Xmlparsernotificationblock) Finishedparser                 errorparser: (xmlparsernotificationblock) ErrorParser; @end


<pre name= "code" class= "OBJC" > #import "MyXMLParser.h" @interface myxmlparser () <nsxmlparserdelegate>{//    The member variable of the record block code Startelementblock _startelementblock;    Endelementblock _endelementblock;    Xmlparsernotificationblock _finishedblock; Xmlparsernotificationblock _errorblock;} Start node name, column such as: Video If this name is detected, you need to instantiate the object @property (strong, nonatomic) nsstring *startelementname;//relay string @property (Strong, nonatomic) nsmutablestring *elementstring, @end @implementation myxmlparser//implement XML parsing in this method. /* Data XML startname start node name startelement start nodes Method endElement End Node method finishedparser document parsing ends. Errorparse document parsing error. */-(void) Xmlparserwithdata: (NSData *) data startname: (NSString *) StartName Startelem ENT: (startelementblock) startelement endElement: (endelementblock) endElement FINISHEDP    Arser: (xmlparsernotificationblock) Finishedparser Errorparser: (xmlparsernotificationblock) errorParser{ Self.startelEmentname = StartName;    Record block Code _startelementblock = startelement;    _endelementblock = endElement;    _finishedblock = Finishedparser;        _errorblock = Errorparser;    Define the parser and start parsing nsxmlparser *parser = [[Nsxmlparser alloc]initwithdata:data]; [Parser setdelegate:self]; Set agent//Start parsing [parser parse]; This method can be implemented by invoking the following methods. } #pragma mark-xml Parser proxy method//The so-called need to interact with the outside, indicating the need to work with the call, notification calls to perform certain operations. 1 Start parsing the document, initializing the data, and not needing to interact with the outside. -(void) Parserdidstartdocument: (Nsxmlparser *) parser{//Instancing The string if (self.elementstring = = nil) {Self.elemen    tstring = [nsmutablestring string]; }}//2 begins parsing elements (the element's head video, needs to instantiate the object, Attributedict needs to set the property)//elements that need to interact with//interact with the outside: ElementName attributedict-(void) Parser: ( Nsxmlparser *) Parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (        NSString *) QName attributes: (nsdictionary *) attributedict{if ([elementname isEqualToString:self.startElementName]) {  Start Part code _startelementblock (attributedict);  }//Before starting the loop to execute the third method, empty the brokered string [self.elementstring setstring:@ "];} 3 found element string (stitching string, no need and external interaction)-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{[ Self.elementstring appendstring:string];} 4 End element parsing, according to ElementName and the stitching content of the third step, determine the object properties, need to interact with the external//Interaction elements: ElementName Relay string-(void) Parser: (Nsxmlparser *) parser    Didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) qName{    NSString *result = [NSString stringWithString:self.elementString]; _endelementblock (elementname, result);} 5 parsing the end of the document, it is usually necessary to call the drop refresh data.    Interactive elements: Notification only-(void) Parserdidenddocument: (Nsxmlparser *) parser{[self.elementstring setstring:@ "]; _finishedblock ();} Parsing error, notifying caller parsing error (requires interaction with outside). Elements of Interaction: notifications only.    -(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@ "Parse error");    [Self.elementstring setstring:@ ""];    It would be better to take a nserror back. _errorblock ();} @end


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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.