iOS comes with XML parsing, Tbxmlparser parsing

Source: Internet
Author: User
Tags uikit

Today looked at the Apple XML parsing, wrote a small demo thought or write something on the blog, after all, a long time has not come up

First, a couple.



Next, look at the engineering catalogue.


This demo is divided into two kinds of analytic mode, one is Apple comes with, first look at the Apple comes with it, the project file is Notexmlparser file, another parsing mode is 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 <Foundation/Foundation.h> @interface notexmlparser:nsobject< nsxmlparserdelegate>//parse out the data, internal is the dictionary type @property (strong,nonatomic) Nsmutablearray * notes;//The name of the current tag, Currenttagname is used to store the element name 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 = [[NS]    Bundle 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 (@ "Parse to fix ...");} Triggered at the beginning of the document, only one time is triggered when parsing begins-(void) Parserdidstartdocument: (Nsxmlparser *) parser{_notes = [Nsmutablearray new];} Trigger on document Error-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@ "%@", ParseError);} Encounter a start tag trigger-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QName attributes: (nsdictionary *) attributedict{//Assign elementname to member variable Curr Enttagname _currenttagname = ElementnamE If the name is Note, remove the ID if ([_currenttagname isequaltostring:@ "Note"]) {NSString * _id = [Attributedict obje       ctforkey:@ "id"];        Instantiate a mutable Dictionary object for storing nsmutabledictionary *dict = [Nsmutabledictionary new];                Put the ID into the dictionary [dict setobject:_id forkey:@ "id"];            Put the mutable dictionary into the variable array set _notes variable [_notes addobject:dict]; }} #pragma mark this method is mainly the main place to parse the text of the element, because special characters such as line feed and carriage return will trigger the method, so to judge and reject the newline and carriage return//Encounter string trigger-(void) Parser: (Nsxmlparser *) Parser foundcharacters: (NSString *) string{//replace carriage return and spaces, where Stringbytrimmingcharactersinset is the method of rejecting characters, [Nscharacterset      Whitespaceandnewlinecharacterset] Specifies that the character set is a newline character and a carriage return character;    string = [string Stringbytrimmingcharactersinset:[nscharacterset whitespaceandnewlinecharacterset]];    if ([string isequaltostring:@ "]) {return;    } nsmutabledictionary * dict = [_notes lastobject]; if ([_currenttagname isequaltostring:@ "CDate"] && dict) {[Dict setobject:string forkey:@]CDate "]; } if ([_currenttagname isequaltostring:@ "Content"] && dict) {[Dict setobject:string forkey:@ ' Conten    T "]; } if ([_currenttagname isequaltostring:@ "userid"] && dict) {[Dict setobject:string forkey:@ ' userid '    ]; }//encountered end tag trigger-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NA    Mespaceuri qualifiedname: (NSString *) qname{self.currenttagname = nil; This method is primarily used to clean up the effects of the elements that have just been parsed, so that the next parsing}//encounters the end of the document trigger-(void) Parserdidenddocument: (Nsxmlparser *) parser{[[ Nsnotificationcenter Defaultcenter] postnotificationname:@ "reloadviewnotification" Object:self.notes UserInfo:nil]    ; Entering this method means that the parsing is completed, some member variables need to be cleaned up, and the data is returned to the presentation layer (the representation graph controller) via broadcast mechanism to deliver the data via broadcast notification to the presentation layer self.notes = nil; @end

The project controller name is: 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 <UIKit/UIKit.h> @interface chonviewcontroller:uitableviewcontroller// Save 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; [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (reloadview:) name:@ "    Reloadviewnotification "Object:nil"; Tbxmlparser resolution//Notestbxmlparser *parser = [Notestbxmlparser new];////Start parsing//[parser start];//NSLog (@ "VI        Ewdidload ");    Apple comes with an analytic notexmlparser * parser = [Notexmlparser new];    Start parsing [parser start];    }-(void) didreceivememorywarning{[Super didreceivememorywarning]; }-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{return 1;} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteGER) section{return self.listdata.count;} -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{UITableView        Cell *cell = [TableView dequeuereusablecellwithidentifier:@ "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 story map is as follows:




As of here has completed the use of Apple's own parser parsing XML is complete, the code is written in very detailed comments!

Next 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 <Foundation/Foundation.h> @interface notestbxmlparser:nsobject// The parsed data inside is 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) {tbxmlelement * 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"]; }//Get id property nsstring *_id = [TBXML valueofattributenamed:@ "id" forelement:noteelement err            Or:nil];                        [Dict setvalue:_id forkey:@ "id"];                                    [_notes addobject:dict];            Noteelement = [TBXML nextsiblingnamed:@ "Note" searchfromelement:noteelement];        }} NSLog (@ "Parse complete ..."); [[Nsnotificationcenter Defaultcenter] Postnotificationname:@ "Reloadviewnotification" Object:self.notes Userinfo:nil];    Self.notes = nil; } @end
OK, finally in the chonviewcontroller.m file in the Viewload method to call the good!

Final statement:

Tbxml parsing XML Document using the DOM parsing mode, through the comparison above, found that he is a very good parsing framework, speed is the fastest in all XML, the following simple introduction of how to use

1. First go to the technical Support website: http://www.tbxml.co.uk/TBXML/TBXML_Free.html Download, extract the Tbxml-headers and Tbxml-code files and add to the project after download is complete

2. The framework does not support arc so in the use of the framework will be reported arc error, here is not the exception error posted, only to provide a solution, you need to modify the project directory testxml-prefix.pch this file, in this file add macros:

#define Arc_enabled



3. Because Tbxml relies on Libz.dylib library, but also need to add this library in the framework of the project, the specific method of adding here does not say, complete the above 3 steps in the compilation can be!


Today, the XML code is pasted out, followed by JSON data parsing, if there is time in the afternoon, make a demo on it, hope to have some help, because I am a novice, haha! Just learned, caught dead!

Yes, the XML file reads ":


Viewdidload




Related Article

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.