Today I read Apple's xml parsing and wrote a small demo. I thought I 'd better write something on my blog. After all, I haven't been up for a long time.
First
Next, let's take a look at the project directory.
This demo has two resolution modes: one is Apple's own, first of all, let's take a look at Apple's own, the project file is the NoteXMLParser file, and the other is the NotesTBXMLParser file.
The NoteXMLParser. h file code is as follows:
//// NoteXMLParser. h // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import
@ Interface NoteXMLParser: NSObject
// The parsed data contains the dictionary type @ property (strong, nonatomic) NSMutableArray * notes; // The Name Of The current tag, currentTagName is used to store the name of the element being parsed @ property (strong, nonatomic) NSString * currentTagName; // start parsing-(void) start; @ end
The NoteXMLParser. m file code is as follows:
//// NoteXMLParser. m // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import "NoteXMLParser. h "@ implementation NoteXMLParser // start parsing-(void) start {NSString * path = [[NSBundle mainBundle] pathForResource: @" Notes "ofType: @" xml "]; NSURL * url = [NSURL fileURLWithPath: path]; // start parsing xml NSXMLParser * parser = [[NSXMLParser alloc] initWithContentsOfURL: url]; parser. delegate = self; [parser parse]; NSLog (@ "Resolution done... ");} // triggered at the beginning of the document. Only one-(void) parserDidStartDocument (NSXMLParser *) parser {_ notes = [NSMutableArray new] is triggered at the start of parsing.} // trigger when a document error occurs-(void) parser :( NSXMLParser *) parser parseerroccurred :( NSError *) parseError {NSLog (@ "% @", parseError );} // encounters a start tag trigger-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI principal :( NSString *) qName attributes :( NSDictionary *) attributeDict {// assign elementName to the member variable currentTagName _ currentTagName = elementName; // if the name is Note, retrieve the id if ([_ currentTagName is1_tostring: @ "Note"]) {NSString * _ id = [attributeDict objectForKey: @ "id"]; // instantiate a variable dictionary object to store NSMutableDictionary * dict = [NSMutableDictionary new]; // put the id in the dictionary [dict setObject: _ id forKey: @ "id"]; // put the variable dictionary into the variable array SET _ notes variable [_ notes addObject: dict] ;}# pragma mark this method is mainly used to parse element texts. This method is also triggered by line breaks, carriage returns, and other special characters, therefore, it is necessary to determine and remove line breaks and carriage returns // trigger when a string is encountered-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {// replace carriage returns and spaces, here, Delimiter is the method for removing characters. [NSCharacterSet delimiter] specifies the character set as line breaks and carriage returns; string = [string delimiter: [NSCharacterSet whitespaceAndNewlineCharacterSet]; if ([string isw.tostring: @ ""]) {return;} NSMutableDictionary * dict = [_ notes lastObject]; if ([_ currentTagName is1_tostring: @ "CDate"] & dict) {[dict setObject: string forKey: @ "CDate"];} if ([_ currentTagName is1_tostring: @ "Content"] & dict) {[dict setObject: string forKey: @ "Content"];} if ([_ currentTagName isw.tostring: @ "UserID"] & dict) {[dict setObject: string forKey: @ "UserID"];} // triggered when an end tag is encountered-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {self. currentTagName = nil; // This method is mainly used to clear the impact of the elements that have just been parsed, so that it does not affect the next parsing} // trigger at the end of the document-(void) parserDidEndDocument :( NSXMLParser *) parser {[nsicationcenter center defacenter center] postNotificationName: @ "reloadViewNotification" object: self. notes userInfo: nil]; // entering this method means that the resolution is complete. You need to clear some member variables and return the data to the presentation layer (indicating the graph Controller) the broadcast mechanism is used to send data to the presentation layer through broadcast notifications. notes = nil;} @ end
Project controller name: chonViewController
The chonViewController. h file code is as follows:
//// ChonViewController. h // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import
@ Interface chonViewController: UITableViewController // Save the data list @ property (nonatomic, strong) NSMutableArray * listdata; @ end
The chonViewController. m file code is as follows:
//// ChonViewController. m // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import "chonViewController. h "# import" NotesTBXMLParser. h "# import" NoteXMLParser. h "@ interface chonViewController () @ end @ implementation chonViewController-(void) viewDidLoad {[super viewDidLoad]; self. navigationItem. leftBarButtonItem = self. editButtonItem; [[nsnotifcenter center defacenter center] addObserver: self selector: @ selector (reloadView :) name: @ "reloadViewNotification" object: nil]; // TBXMLParser parsing // NotesTBXMLParser * parser = [NotesTBXMLParser new]; // start parsing // [parser start]; // NSLog (@ "viewDidLoad "); // Apple's built-in parsing NoteXMLParser * parser = [NoteXMLParser new]; // start parsing [parser start];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning];}-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView {return 1;}-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. listdata. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {UITableViewCell * cell = [tableView progress: @ "Cell" forIndexPath: indexPath]; NSMutableDictionary * dict = self. listdata [indexPath. row]; cell. textLabel. text = [dict objectForKey: @ "Content"]; cell. detailTextLabel. text = [dict objectForKey: @ "CDate"]; return cell;} # pragma mark-processing notification-(void) reloadView :( NSNotification *) notification {NSMutableArray * resList = [notification object]; self. listdata = resList; [self. tableView reloadData];} @ end
The layout of the story is as follows:
As of now, the parsing of xml has been completed by using the parser that comes with Apple. The comments in the Code are very detailed!
Next, let's take a look at the TBXMLParser parsing mode.
The NotesTBXMLParser. h file code is as follows:
/// NotesTBXMLParser. h // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import
@ Interface NotesTBXMLParser: NSObject // The parsed data contains the dictionary type @ property (strong, nonatomic) NSMutableArray * notes; // start parsing-(void) start; @ end
The NotesTBXMLParser. m file code is as follows:
/// NotesTBXMLParser. m // TestXML // Created by choni on 14-5-16. // Copyright (c) 2014 choni. all rights reserved. // # import "NotesTBXMLParser. h "# import" TBXML. h "@ implementation NotesTBXMLParser // start parsing-(void) start {_ notes = [NSMutableArray new]; TBXML * tbxml = [[TBXML alloc] initWithXMLFile: @" Notes. xml "error: nil]; TBXMLElement * root = tbxml. rootXMLElement; // if root element is validif (root) {T BXMLElement * noteElement = [TBXML childElementNamed: @ "Note" parentElement: root]; while (noteElement! = Nil) {NSMutableDictionary * dict = [NSMutableDictionary new]; TBXMLElement * CDateElement = [TBXML childElementNamed: @ "CDate" parentElement: noteElement]; if (CDateElement! = Nil) {NSString * CDate = [TBXML textForElement: CDateElement]; NSLog (@ "CDate =%@", CDate); [dict setValue: CDate forKey: @ "CDate"];} TBXMLElement * ContentElement = [TBXML childElementNamed: @ "Content" parentElement: noteElement]; if (ContentElement! = Nil) {NSString * Content = [TBXML textForElement: ContentElement]; [dict setValue: Content forKey: @ "Content"];} TBXMLElement * UserIDElement = [TBXML childElementNamed: @ "UserID" parentElement: noteElement]; if (UserIDElement! = Nil) {NSString * UserID = [TBXML textForElement: UserIDElement]; [dict setValue: UserID forKey: @ "UserID"];} // obtain the ID attribute NSString * _ id = [TBXML valueOfAttributeNamed: @ "id" forElement: noteElement error: nil]; [dict setValue: _ id forKey: @ "id"]; [_ notes addObject: dict]; noteElement = [TBXML nextSiblingNamed: @ "Note" searchFromElement: noteElement] ;}} NSLog (@ "Resolution completed... "); [[nsicationicationcenter defacenter center] postNotificationName: @" reloadViewNotification "object: self. notes userInfo: nil]; self. notes = nil;} @ end
OK. Finally, you can call the viewLoad method in the chonVIewController. m file!
Final Statement:
The xml document for TBXML parsing adopts the DOM parsing mode. Through the comparison above, we found that it is a very good parsing framework, and the speed is the fastest in all xml. The following briefly introduces how to use it.
1. first go to the Technical Support site: http://www.tbxml.co.uk/TBXML/TBXML_Free.html download, after the download is complete decompress the TBXML-Headers and TBXML-Code files and add to the Project
2. this framework does not support ARC so when using this framework to run will report the ARC error, here is not the exception error posted, only provide a solution, you need to modify the project directory in the TestXML-Prefix.pch this file, add a macro to this file: for example
# Define ARC_ENABLED
3. because TBXML depends on libz. dylib library, you also need to add this library in the Framework of the project. The specific addition method is not mentioned here. After completing the above three steps, compile it!
I posted the xml code first today, and then parse the json data. If I have time in the afternoon, I will make a demo. I hope it will be helpful, because I am a newbie, haha! I just learned, but it's ugly! <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + ttTBy6OseG1szsS8/sTayN3I58/C ":
ViewDidLoad