IOS Xml/json Parsing

Source: Internet
Author: User

<a target=_blank href= "http://download.csdn.net/detail/vaercly/7908319" > Click to open Download link Ios,xml/json parse </a>// finterpretervc.m//finterpreter////Created by Lanouhn on 14-9-11.//Copyright (c) 2014 [email protected] Chen Conglei. All rights reserved.//#import "FInterPreterVC.h" #import "Person.h" #import "GDataXMLNode.h" #import "JSONKit.h" @ Interface FINTERPRETERVC () <NSXMLParserDelegate> @property (nonatomic, retain) Nsmutablearray *arr;// Used to store the person object @property (nonatomic, retain) person *per;//used to store information @property (nonatomic, retain) nsstring *str;// Store read string @end@implementation finterpretervc-(ID) initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *)    nibbundleornil{self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]; if (self) {//Custom initialization} return to self;} /** * Resolution: In accordance with a well-agreed format (illusion), there are background developers, in accordance with the format of the data, the front-end in accordance with the format of data (remember: This format is determined by the background developers, we have no right to determine) the essence of the resolution: In accordance with the agreed-upon format of the process of extracting the The format of the row: XML and JSON format XML parsing two analytic principles: Sax parsing: The parsing mechanism based on the event callback, is to useprotocols, and proxies. Sax parsing is line-by-row parsing, read into the data only one line, a line of parsing, so the sax parsing memory is small, suitable for big data parsing DOM parsing: one-time to read all the content into memory, the content read into the tree structure, layer-wise analysis, suitable for small data parsing */-(void) Viewdid    load{[Super Viewdidload];    Do any additional setup after loading the view.    Self.view.backgroundColor = [Uicolor Whitecolor];    UILabel *xmllabel = [[UILabel alloc] Initwithframe:cgrectmake (110, 30, 100, 30)];    Xmllabel.text = @ "XML parsing";    Xmllabel.textalignment = Nstextalignmentcenter;    [Self.view Addsubview:xmllabel];        [Xmllabel release];    UILabel *jsonlabel = [[UILabel alloc] Initwithframe:cgrectmake (110, 200, 100, 30)];    Jsonlabel.text = @ "JSON parsing";    Jsonlabel.textalignment = Nstextalignmentcenter;    [Self.view Addsubview:jsonlabel];        [Jsonlabel release];    Nsarray *titles = @[@ "sax parsing", @ "DOM parsing the first way", @ "DOM parsing the second way", @ "system parsing", @ "string parsing", @ "array parsing", @ "dictionary parsing", @ "data parsing"]; Nsarray *methods = @[@ "Handlesax:", @ "HANDLEDOMBTN1:", @ "HANDLEDOMBTN2:", @ "Handlesystemjson:", @ "HANDLESTRBTN:", @ " HANDLEARRBTN: "@" HANDLEDICBTN: "@" HANDLEDATABTN: "];    CGFloat height = 70;        for (int i = 0; i < 8; i++) {UIButton *btn = [UIButton Buttonwithtype:uibuttontypesystem];        Btn.frame = CGRectMake (max, height, 200, 30);        Btn.backgroundcolor = [Uicolor Greencolor];        [BTN Settitle:titles[i] forstate:uicontrolstatenormal];        SEL selector = nsselectorfromstring (methods[i]);        [Btn addtarget:self action:selector forcontrolevents:uicontroleventtouchupinside];        [Self.view ADDSUBVIEW:BTN];        if (i = = 2) {height = 200;    } height + = 40;    } UILabel *text = [[UILabel alloc] Initwithframe:cgrectmake (110, 470, 100, 30)];    Text.text = @ "Come on!";    Text.textalignment = Nstextalignmentcenter;    [Self.view Addsubview:text]; [Text release];} Sax parsing-(void) Handlesax: (UIButton *) btn{//1 get resolved file path nsstring *xmlpath = [[NSBundle Mainbundle] pathforresource:@    "Person" oftype:@ "xml";    2 Initialize the NSData object according to the file path nsdata *data = [NSData Datawithcontentsoffile:xmlpath]; 3 GenBuild Parse Tool object Nsxmlparser *parser = [[Nsxmlparser alloc] initwithdata:data];    4 Set proxy parser.delegate = self; 5 Start parsing [parser parse];} #pragma mark-nsxmlparserdetegate//trigger when reading to the start tag-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) ElementName NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QName attributes: (Nsdictionary *)    attributedict{NSLog (@ "Start%@", attributedict); When the data is stored in the properties of the start tag, the processing method if ([ElementName isequaltostring:@ "Persons"]) {//Array space Self.arr = [nsmutablear    Ray Array]; } else if ([elementname isequaltostring:@ "Person"]) {//Open space for person object self.per = [[Person alloc] init] Auto        Release];    [Self.arr AddObject:self.per];    } else if ([elementname isequaltostring:@ "name"]) {self.per.name = attributedict[@ "name"];    } else if ([ElementName isequaltostring:@ "Gender"]) {Self.per.gender = attributedict[@ "gender"]; } else if ([ElementName isequaltostring:@ "Age"]) {sElf.per.age = attributedict[@ "Age"];    } else if ([ElementName isequaltostring:@ "PhoneNumber"]) {Self.per.phoneNumber = attributedict[@ "PhoneNumber"];    } else if ([ElementName isequaltostring:@ "ImageName"]) {self.per.imageName = attributedict[@ "ImageName"]; }//When the data is stored in the start tag and the end tag, the processing method/* if ([elementname isequaltostring:@ "Persons"]) {//Array space self.    arr = [Nsmutablearray array]; } else if ([elementname isequaltostring:@ "Person"]) {//Open space for perosn object self.per = [[Person alloc] init] Auto    Release]; */}//-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string{//NSLog (@ "Content%@") when reading the contents of the label    string); Save read Data//Self.str = string;} Trigger when reading to end tag-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *)        NamespaceURI qualifiedname: (NSString *) qname{NSLog (@ "End%@", elementname); /* if ([elementname isequaltostring:@ "name"]) {selF.per.name = Self.str;    } else if ([ElementName isequaltostring:@ "Gender"]) {self.per.gender = Self.str;    } else if ([ElementName isequaltostring:@ "Age"]) {self.per.age = Self.str;    } else if ([ElementName isequaltostring:@ "PhoneNumber"]) {self.per.phoneNumber = Self.str;    } else if ([ElementName isequaltostring:@ "ImageName"]) {self.per.imageName = Self.str; } else if ([elementname isequaltostring:@ "Person"]) {//When reading the end tag of person, the person object has been assigned and stored in the array [Self.arr AD    DObject:self.per];    */}//when parsing is complete-(void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@ "Game Over"); NSLog (@ "%@", Self.arr);} Dom parsing the first way/** * DOM Parsing uses an open source, efficient parsing tool provided by Google Gdataxmlnode, which works 10 times times faster than Nsxmlparser. Usage: 1 First import system dynamic link library Libxml2.2.dyli B 2 in Buildsettings, add/USR/INCLUDE/LIBXML2 3 in the header Search path in buildsettings add-LXML2 */-in other Linker flags (voi d) HANDLEDOMBTN1: (UIButton *) btn{//1 get path to parse file nsstring *xmlpath = [[NSBundle mAinbundle] pathforresource:@ "person" oftype:@ "xml"];    2 Initialize XML string NSString *xmlstr = [NSString stringwithcontentsoffile:xmlpath encoding:nsutf8stringencoding Error:nil]; 3 Initializes a Gdataxmldocument object because all the content is read from the object during parsing (so that the object that needs to be parsed exists) gdataxmldocument *document = [[Gdataxmldocument    Alloc] Initwithxmlstring:xmlstr options:0 Error:nil];    4 Getting the root node gdataxmlelement *rootelement = [Document RootElement];    5 Gets all child nodes of the root node nsarray *personelements = [rootelement elementsforname:@ "person"]; 6 get the array first to get each person node, and then get the child node under the PEROSN node for (gdataxmlelement *element in personelements) {//Get the name under the PEROSN node        Node Gdataxmlelement *nameelement = [[Element elementsforname:@ "name"] firstobject];        Get the gender node under the perosn node gdataxmlelement *genderelement = [[Element elementsforname:@ "gender"] firstobject];        Gets the age node under the perosn node gdataxmlelement *ageelement = [[Element elementsforname:@ "age"] firstobject];       Get the ImageName node under the PEROSN node Gdataxmlelement *imagenameelement = [[Element elementsforname:@ "ImageName"] firstobject]; Gets the PhoneNumber node under the perosn node gdataxmlelement *phonenumberelement = [element elementsforname:@ "PhoneNumber"] firstOb        Ject];        1 Get start tag and end tag Value/* NSString *name = [Nameelement stringvalue];        NSString *gender = [Genderelement stringvalue];        NSString *age = [Ageelement stringvalue];        NSString *imagename = [Imagenameelement stringvalue];        NSString *phonenumber = [Phonenumberelement stringvalue];         NSLog (@ "=======%@%@%@%@%@", name, gender, age, ImageName, PhoneNumber); *///2 gets the class that corresponds to the data//attribute stored in the attribute in the Gdataxmlnode gdataxmlnode *namenode = [Nameelement attributeforname:@ "n        Ame "];        Gdataxmlnode *gendernode = [genderelement attributeforname:@ "gender"];        Gdataxmlnode *agenode = [ageelement attributeforname:@ "age"];    Gdataxmlnode *imagenamenode = [imagenameelement attributeforname:@ "ImageName"];    Gdataxmlnode *phonenumbernode = [phonenumberelement attributeforname:@ "PhoneNumber"];        NSString *name = [NameNode stringvalue];        NSString *gender = [Gendernode stringvalue];        NSString *age = [Agenode stringvalue];        NSString *phonenumber = [Phonenumbernode stringvalue];        NSString *imagename = [Imagenamenode stringvalue];    NSLog (@ "%@%@%@%@%@", name, gender, age, PhoneNumber, imageName); }}-(void) HANDLEDOMBTN2: (UIButton *) btn{//1 get path to parse file nsstring *xmlpath = [[NSBundle mainbundle] pathforresource:@ "    Person "oftype:@" xml "];    2 Initialize XML string NSString *xmlstr = [NSString stringwithcontentsoffile:xmlpath encoding:nsutf8stringencoding Error:nil]; 3 Initializes a Gdataxmldocument object because all the content is read from the object during parsing (so that the object that needs to be parsed exists) gdataxmldocument *document = [[Gdataxmldocument    Alloc] Initwithxmlstring:xmlstr options:0 Error:nil]; /** * XPath As long as the given relative path, such as://name, as long as the name can be reached, you can get the name to *///4 get all the name node Nsarray *nameelements =[Document Nodesforxpath:@ "//name" error:nil];    Get all gender nodes nsarray *genderelements = [Document nodesforxpath:@ "//gender" error:nil];    Get all the age nodes nsarray *ageelements = [Document nodesforxpath:@ "//age" error:nil];    Get all imageName nodes Nsarray *imagenameelements = [Document nodesforxpath:@ "//imagename" error:nil];    Get all phonenumber nodes Nsarray *phonenumberelements = [Document nodesforxpath:@ "//phonenumber" error:nil];        By looping out each node for (int i = 0; i < 3; i++) {gdataxmlelement *nameelement = nameelements[i];        Gdataxmlelement *genderelement = genderelements[i];        Gdataxmlelement *ageelement = ageelements[i];        Gdataxmlelement *imagenameelement = imagenameelements[i];        Gdataxmlelement *phonenumberelement = phonenumberelements[i];        NSString *name = [Nameelement stringvalue];        NSString *gender = [Genderelement stringvalue];        NSString *age = [Ageelement stringvalue]; NSString *imagename = [imagenameelementStringValue];        NSString *phonenumber = [Phonenumberelement stringvalue];    NSLog (@ "-------%@%@%@%@%@", name, gender, age, ImageName, PhoneNumber); }}//System parsing mode-(void) Handlesystemjson: (UIButton *) btn{//1 get file path nsstring *filepath = [[NSBundle Mainbundle] Pathforr    esource:@ "Student" oftype:@ "json"];    2 Initialize NSData object NSData *data = [NSData Datawithcontentsoffile:filepath]; 3 parsing Nsmutablearray *arr = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error    : nil]; NSLog (@ "%@", arr);} The parsing method of the Jsonkit class/** * For the parsing method provided by Jsonkit, is the way to add a classification to the Nsstring,nsdata, in the classification to add a resolution. Efficiency is second only to the system. Parses the JSON format data into nsarray,nsdictionary. The method of classification added for nsarray,nsdictionary is to convert OC objects into JSON format strings. * */-(void) HANDLESTRBTN: (UIButton *) btn{//1 get file path nsstring *filepath = [[NSBundle mainbundle] pathforresource:@ "S    Tudent "oftype:@" json "]; 2 Initialize NSString object NSString *jsonstr = [NSString stringwithcontentsoffile:filepath encoding:nsutf8stringencoding ErroR:nil];    3 parsing Nsarray *arr = [Jsonstr objectfromjsonstring]; NSLog (@ "%@", arr);}    -(void) HANDLEARRBTN: (UIButton *) btn{//1 converts an array of OC to JSON formatted string Nsarray *arr = @[@1,@ "BB", @ "CC", @ "DD", @ "ee"];    Conversion NSString *jsonstr = [arr jsonstring];    NSLog (@ "%@", jsonstr);    2 parsing NSString *str = [Jsonstr objectfromjsonstring]; NSLog (@ "%@", str);} -(void) HANDLEDICBTN: (UIButton *) btn{//1 convert OC Dictionary to JSON formatted string nsdictionary *dic = @{@ "name": @1,@ "Gender": @ "man" @ "AG"    E ": @" 18 "};    Conversion NSString *JSONSTR = [dic jsonstring];    NSLog (@ "%@", jsonstr);    2 parsing NSString *str = [Jsonstr objectfromjsonstring]; NSLog (@ "%@", str);} -(void) HANDLEDATABTN: (UIButton *) btn{//1 get file path nsstring *fileparth = [[NSBundle mainbundle] pathforresource:@ "Stu    Dent "oftype:@" JSON "];    2 Initialize NSData object NSData *jsondata = [NSData Datawithcontentsoffile:fileparth];    3 parsing Nsarray *arr = [Jsondata objectfromjsondata]; NSLog (@ "%@", arr);} -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} /* #pragma mark-navigation//in a storyboard-based application, you'll often want to do a little preparation before Nav igation-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{//Get The new view controller using [Segu    E Destinationviewcontroller]. Pass the selected object to the new view Controller.}    */-(void) dealloc{Self.arr = nil;    Self.per = nil;    Self.str = nil; [Super Dealloc];} @end

IOS Xml/json Parsing

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.