IOS XML/JSON Parsing

Source: Internet
Author: User

IOS XML/JSON Parsing

Click to open the download link for iOS, XML/JSON parsing // FInterPreterVC. m // FInterpreter /// Created by lanouhn on 14-9-11. // Copyright (c) 2014 vaercly@163.com Chen conglei. all rights reserved. // # import "FInterPreterVC. h "# import" Person. h "# import" GDataXMLNode. h "# import" JSONKit. h "@ interface FInterPreterVC ()
 
  
@ 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 the read string @ end @ implementation FInterPreterVC-(id) initWithNibName :( NSString *) nibNameOrNil bundle :( NSBundle *) into {self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil]; if (self) {// Custom initialization} return self ;}/*** Resolution: according to a agreed format (hypothetical), there are background developers who store data according to the format, and the front end retrieves data according to the format (remember: this format is determined by the background developers and we do not have the right to decide) essence of resolution: the process of extracting the data we want according to the agreed format is more popular today: XML and JSON format XML parsing principles: SAX parsing: An Event Callback-based parsing mechanism that uses protocols and proxies. SAX Parsing is a row-by-row parsing. When reading data, it reads only one row and one row for parsing. Therefore, SAX parsing occupies a small amount of memory and is suitable for DOM parsing for big data parsing: read all the content into the memory at a time, read the content into a tree structure, layer-by-layer resolution, suitable for small data parsing */-(void) viewDidLoad {[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 resolution", @ "first method of Dom resolution ", @ "second method of Dom Parsing", @ "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 buttonWit HType: UIButtonTypeSystem]; btn. frame = CGRectMake (60, 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 = [[UILa Bel alloc] initWithFrame: CGRectMake (110,470,100, 30)]; text. text = @ "Come on! "; Text. textAlignment = NSTextAlignmentCenter; [self. view addSubview: text]; [text release];} // SAX resolution-(void) handleSAX :( UIButton *) btn {// 1 obtain the parsed file path NSString * xmlPath = [[NSBundle mainBundle] pathForResource: @ "Person" ofType: @ "xml"]; // 2 initialize the NSData object NSData * data = [NSData dataWithContentsOfFile: xmlPath] According to the file path; // 3 create the parsing Tool Object NSXMLParser * parser = [[NSXMLParser alloc] initWithData: data]; // 4 set the proxy parser. delegate = self; // 5 start parsing [parser parse];} # pragma mark-NSXMLParserDetegate // triggered when the start tag is read-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI identifier :( NSString *) qName attributes :( NSDictionary *) attributeDict {NSLog (@ "start % @", attributeDict ); // when data is stored to the attribute of the start tag, the processing method is if ([elementName isinclutostring: @ "Persons"]) {// opens up space for the array self. arr = [NSMutableArray array];} else if ([elementName isinclutostring: @ "person"]) {// open up space for the person object self. per = [[[Person alloc] init] autorelease]; [self. arr addObject: self. per];} else if ([elementName isinclutostring: @ "name"]) {self. per. name = attributeDict [@ "name"];} else if ([elementName isinclutostring: @ "gender"]) {self. per. gender = attributeDict [@ "gender"];} else if ([elementName isinclutostring: @ "age"]) {self. per. age = attributeDict [@ "age"];} else if ([elementName is1_tostring: @ "phoneNumber"]) {self. per. phoneNumber = attributeDict [@ "phoneNumber"];} else if ([elementName is1_tostring: @ "imageName"]) {self. per. imageName = attributeDict [@ "imageName"];} // processing method when data is stored to the start and end tags/* if ([elementName isinclutostring: @ "Persons"]) {// open up space self for the array. arr = [NSMutableArray array];} else if ([elementName isinclutostring: @ "person"]) {// open up space for the perosn object self. per = [[[Person alloc] init] autorelease];} * // triggered when the content after the tag is read-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {// NSLog (@ "content % @", string); // Save the read data // self. str = string;} // triggered when the end tag is read-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {NSLog (@ "end % @", elementName);/* if ([elementName isinclutostring: @ "name"]) {self. per. name = self. str;} else if ([elementName isinclutostring: @ "gender"]) {self. per. gender = self. str;} else if ([elementName isinclutostring: @ "age"]) {self. per. age = self. str;} else if ([elementName isinclutostring: @ "phoneNumber"]) {self. per. phoneNumber = self. str;} else if ([elementName isinclutostring: @ "imageName"]) {self. per. imageName = self. str;} else if ([elementName isinclutostring: @ "person"]) {// when the end tag of person is read, the person object has been assigned a value and stored in the array [self. arr addObject: self. per];} * // triggered after resolution-(void) parserDidEndDocument :( NSXMLParser *) parser {NSLog (@ "game over "); NSLog (@ "% @", self. arr);} // The first method of DOM parsing/*** DOM parsing uses an open-source and efficient parsing tool GDataXMLNode provided by Google, its effect is 10 times faster than that of NSXMLParser: 1. Import libxml2.2.dylib 2 to the system dynamic link library and add/usr/include/libxml2 3 to Other Linker Flags in buildset.pdf-lxml2 */-(void) in Header Search Path of buildset2) handleDomBtn1 :( UIButton *) btn {// 1 obtain the path of the parsing file NSString * xmlPath = [[NSBundle mainBundle] pathForResource: @ "Person" ofType: @ "xml"]; // 2 initialize the xml string NSString * xmlStr = [NSString stringWithContentsOfFile: xmlPath encoding: NSUTF8StringEncoding error: nil]; // 3 initialize a GDataXMLDocument object, because all the content during parsing is read from this object (so the content to be parsed must exist in this object) GDataXMLDocument * document = [[GDataXMLDocument alloc] initWithXMLString: xmlStr options: 0 error: nil]; // 4 get the root node GDataXMLElement * rootElement = [document rootElement]; // 5 get all the child nodes of the root node NSArray * personElements = [rootElement elementsForName: @ "person"]; // 6 first obtain the array to obtain each person node, and then obtain the child node under the perosn node for (GDataXMLElement * element in personElements) {// obtain the name node GDataXMLElement * nameElement = [[element elementsForName: @ "name"] firstObject] under the perosn node; // obtain the gender node GDataXMLElement * genderElement = [[element elementsForName: @ "gender"] firstObject] under the perosn node; // obtain the age node GDataXMLElement * ageElement = [[element elementsForName: @ "age"] firstObject] under the perosn node; // obtain the imageName node GDataXMLElement * imageNameElement = [[element elementsForName: @ "imageName"] firstObject] under the perosn node; // obtain the GDataXMLElement of the phoneNumber node under the perosn node * phoneNumberElement = [[element elementsForName: @ "phoneNumber"] firstObject]; // 1 obtain the start and end tags/* 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 obtain the data stored in the performance attribute. // The class corresponding to the attribute is GDataXMLNode * nameNode = [nameElement attributeForName: @ "name"]; required * genderNode = [genderElement attributeForName: @ "gender"]; GDataXMLNode * ageNode = [ageElement attributeForName: @ "age"]; required * 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 obtain the path of the parsing file NSString * xmlPath = [[NSBundle mainBundle] pathForResource: @ "Person" ofType: @ "xml"]; // 2 initialize the xml string NSString * xmlStr = [NSString stringWithContentsOfFile: xmlPath encoding: NSUTF8StringEncoding error: nil]; // 3 initialize a GDataXMLDocument object, because all the content during parsing is read from this object (so the content to be parsed must exist in this object) GDataXMLDocument * document = [[GDataXMLDocument alloc] initWithXMLString: xmlStr options: 0 error: nil];/*** XPath only needs to be given a relative path, for example, // name, as long as it can reach the name, you can get the name * // 4 to get all the name nodes NSArray * nameElements = [document nodesForXPath: @ "// name" error: nil]; // obtain all gender nodes NSArray * genderElements = [document nodesForXPath: @ "// gender" error: nil]; // obtain all age nodes NSArray * ageElements = [document nodesForXPath: @ "// age" error: nil]; // obtain all imageName nodes NSArray * imageNameElements = [document nodesForXPath: @ "// imageName" error: nil]; // obtain all the phoneNumber nodes NSArray * phoneNumberElements = [document nodesForXPath: @ "// phoneNumber" error: nil]; // obtain 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 = [imageNameElement stringValue]; NSString * phoneNumber = [phoneNumberElement stringValue]; NSLog (@ "------- % @", name, gender, age, imageName, phoneNumber) ;}// system resolution method-(void) handleSystemJSON :( UIButton *) btn {// 1 obtain the file path NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "Student" ofType: @ "json"]; // 2 initialize NSData object NSData * data = [NSData dataWithContentsOfFile: filePath]; // 3 parse NSMutableArray * arr = [NSJSONSerialization JSONObjectWithData: data options: Unknown error: nil]; NSLog (@ "% @", arr);} // JSONKit class resolution method/*** the parsing method provided by JSONKit, which is used to add a category for NSString and NSData, the resolution method is added to the category. efficiency is second only to the system. parses json data into NSArray and NSDictionary. for NSArray and NSDictionary, the classification method is to convert OC objects into JSON strings. **/-(void) handleStrBtn :( UIButton *) btn {// 1 get the file path NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "Student" ofType: @ "json"]; // 2 initialize NSString object NSString * jsonStr = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil]; // 3 parse NSArray * arr = [jsonStr objectFromJSONString]; NSLog (@ "% @", arr);}-(void) handleArrBtn :( UIButton *) btn {// 1 convert the OC array to a json formatted string NSArray * arr = @ [@ 1, @ "bb", @ "cc", @ "dd ", @ "ee"]; // converts NSString * jsonStr = [arr JSONString]; NSLog (@ "% @", jsonStr ); // 2 parse NSString * str = [jsonStr objectFromJSONString]; NSLog (@ "% @", str) ;}- (void) handleDicBtn :( UIButton *) btn {// 1 convert the OC dictionary to a json formatted string NSDictionary * dic ={ @ "name": @ 1, @ "gender": @ "man ", @ "age": @ "18"}; // convert NSString * jsonStr = [dic JSONString]; NSLog (@ "% @", jsonStr ); // 2 parse NSString * str = [jsonStr objectFromJSONString]; NSLog (@ "% @", str) ;}- (void) handleDataBtn :( UIButton *) btn {// 1 obtain the file path NSString * fileParth = [[NSBundle mainBundle] pathForResource: @ "Student" ofType: @ "json"]; // 2 initialize NSData object NSData * jsonData = [NSData dataWithContentsOfFile: fileParth]; // 3 parse NSArray * arr = [jsonData objectFromJSONData]; NSLog (@ "% @", arr);}-(void) didreceivemorywarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} /* # pragma mark-Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation-(void) prepareForSegue :( UIStoryboardSegue *) segue sender :( id) sender {// Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller .} */-(void) dealloc {self. arr = nil; self. per = nil; self. str = nil; [super dealloc];} @ end
 

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.