IOS advanced learning-network data parsing and ios advanced data parsing

Source: Internet
Author: User

IOS advanced learning-network data parsing and ios advanced data parsing

I. Basic concepts of analysis

  • "Resolution": extract data in the specified format.
  • Prerequisites for parsing: The format is agreed in advance. The data provider provides data in the format and the data retrieval party obtains data in the format.
  • Common parsing for iOS development: XML parsing and JSON parsing.

Ii. XML Data Structure

  • XML: Extensible Markup language (Extensible Markup language), one of the mainstream data formats, can be used to store and transmit data.
  • XML data format functions: data exchange and content management, used as configuration files.
  • Syntax of XML data structure: 1) Declaration; 2) nodes are represented by a bunch of labels; 3) the root node is the Start Node. Only one node can be nested. 4) nodes can have values, stored in a pair of tags.

III. The SAX tool and DOM tool used for XML Data Structure Parsing

1. SAX tool:

  • SAX parsing: SAX (Simple API for XML) parses data row by row based on the time-driven parsing method. (Protocol callback mechanism is adopted ).
  • NSXMLParser is an XML parsing class provided by iOS. It parses data using the SAX method.
  • The parsing process is called back by the NSXMLParserDelegate protocol method.
  • Resolution Process: start tag-> value-> end tag-> Value
  • Initialize NSXMLParser:
# Pragma mark-sax Parse XML file-(IBAction) saxParserActionXMLDocument :( UIButton *) sender {// 1. obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: @ "StudentsInfo_XML" ofType: @ "txt"]; // 2. obtain NSData * data = [NSData dataWithContentsOfFile: path]; // 3. set SAX parsing and associate the relevant xml file NSXMLParser * parser = [[NSXMLParser alloc] initWithData: data]; // 4. sets the proxy parser. delegate = self; // 5. start parsing [parser parse];}
  • Protocol method of NSXMLParserDelegate:
# Protocol method of pragma mark-NSXMLParserDelegate // 1. file Parsing (beginning of report parsing)-(void) parserDidStartDocument :( NSXMLParser *) parser {// initialize the array self. dataArray = [[NSMutableArray alloc] init];} // 2. processing Function for tag initiation (that is, the start of the report element and the attribute of the element)-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName attributes :( NSDictionary <NSString *, NSString *> *) attributeDict {// obtain relevant data based on the required tags if ([elementName isinclutostring: @ "student"]) {Student * stu = [[Student alloc] init]; // Add the data object to the array [self. dataArray addObject: stu];} // pass the current tag value to the property self of the record tag. currentElement = elementName;} // 3. parse the content in the tag and assign the value to the object-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {// retrieve the relevant student object from the array, each time the last element is retrieved from the array, Student * stu = [self. dataArray lastObject]; // KVC value assignment [stu setValue: string forKey: self. currentElement];} // 4. end tag-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {self. currentElement = nil;} // 5. end document parsing (end of report parsing)-(void) parserDidEndDocument :( NSXMLParser *) parser {for (Student * stu in self. dataArray) {NSLog (@ "name = % @, gender = % @, age = % ld, holobby = % @", stu. name, stu. gender, stu. age, stu. holobby) ;}// 6. error Handling-(void) parser :( NSXMLParser *) parser parseerroccurred :( NSError *) parseError {NSLog (@ "error = % @", parseError );}

2. DOM tools

  • DOM parsing: when DOM (Document Object Model) is used to parse XML, read the entire XML Document and construct a memory-resident tree structure (number of nodes). By traversing the tree structure, you can retrieve any XML node, read its attributes and values. In addition, you can use XPath to directly query XML nodes.
  • GDataXMLNode: Uses DOM to parse data. iOS contains a C language dynamic link library libxml2.dylib (changed to libxml2.tab after xcode7), which is faster than NSXMLParser; GDataXMLNode is an open-source XML parsing class provided by Google. It encapsulates libxml2.tab in Objective-C. It can read and write small or medium xml documents and supports Path syntax.
  • GDataXMLNode usage:
  • Obtain the GDataXMLNode. h/m file and add the GDataXMLNode. h/m file to the project.
  • Add the "libxml2.tab" dynamic library to the project.
  • At this time, an error will be reported during compilation:
  • The reason is as follows:
  • Specific operations:
  • On the "Build Settings" page of the project, locate the "Header Search Path" item, add "/usr/include/libxml2", and find the "Other Linker Flags" item, add "-lxml2 ".
  • If the project reports the following error during compilation:
  • This error is caused by a non-ARC file that cannot be run in the ARC project. Solution: Find the corresponding project file, add-fno-objc-arc, and add-fobjc-arc. Figure:
  • Import the "GDataXMLNode. h" file to the header file. If the project can be compiled, GDataXMLNode is successfully added.
  • Sample Code:
# Pragma mark-dom Parse XML file-(IBAction) domParserActionXMLDocument :( id) sender {// first introduce the dynamic library // 1. obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: @ "StudentsInfo_XML" ofType: @ "txt"]; // 2. obtain NSData * data = [NSData dataWithContentsOfFile: path]; // initialize the array of stored data self. dataArray = [[NSMutableArray alloc] init]; // 3. set DOM resolution (create resolution document) GDataXMLDocument * document = [[GDataXMLDocument alloc] initWithData: data options: 0 error: nil]; // 4. obtain the root node GDataXMLElement * rootElement = document. rootElement; // 5. obtain the corresponding sub-node for (GDataXMLElement * studentElement in rootElement. children) {Student * stu = [[Student alloc] init]; // retrieve the subnode of the subnode for (GDataXMLElement * stuElement in studentElement. children) {NSLog (@ "stuElement = % @", stuElement); // assign a value to the student object based on the tag // stuElement. name tag name // stuElement. value of the stringValue tag [stu setValue: stuElement. stringValue forKey: stuElement. name];} [self. dataArray addObject: stu];} for (Student * stu in self. dataArray) {NSLog (@ "name = % @, gender = % @, age = % ld, holobby = % @", stu. name, stu. gender, stu. age, stu. holobby );}}

Iv. JSON Data Structure

1. Concept of JSON Data Structure: JSON (JavaScript Object Notation) is a lightweight data exchange format. JSON is in a language-independent text format, which is easy to read and write, and easy to parse and generate by machines. These features make JSON an ideal data exchange language.

2. JSON files have two structures:

  • Object: the set of "name/value" pairs. In different languages, it is understood as an object, record, structure, Dictionary, hash table, key list, or associated array. Start with "{" and end with "}", which is a set of "name/value" pairs. Names and values are separated. Multiple "name/value" pairs are separated.
  • Array: an ordered list. In most languages, it is understood as an array. Start with "[" and end with "]". Data in the middle is separated.
  • Data Types in JSON: String, value, BOOL, object, and array.
  • Functions of JSON Data Structure: data exchange, content management, and configuration files.
  • JSON data example:

5. Third-party frameworks and system methods used for JSON Data Structure Parsing

1. parse JSON data using the system method:

# Pragma mark-JSON data parsing in the system-(IBAction) foundationParserActionJSONDocument :( id) sender {// 1. obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: @ "StudentInfo_json" ofType: @ "txt"]; // 2. obtain NSData * data = [NSData dataWithContentsOfFile: path]; // initialize the array of stored data self. dataArray = [[NSMutableArray alloc] init]; // 3. parse data NSArray * resultArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: nil]; // 4. traverse the array and assign the value of for (NSDictionary * dict in resultArray) {Student * stu = [[Student alloc] init]; [stu setValuesForKeysWithDictionary: dict]; [self. dataArray addObject: stu];} for (Student * stu in self. dataArray) {NSLog (@ "name = % @, gender = % @, age = % ld, holobby = % @", stu. name, stu. gender, stu. age, stu. holobby );}}

2. Use JSONKit to parse json data: first introduce the JSONKit. h/m file of the third-party framework, and use the non-ARC file in the ARC project according to the above steps.

# Pragma mark-use JSONKit to parse json data-(IBAction) jsonKitParserActionJSONDocument :( id) sender {// 1. obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: @ "StudentInfo_json" ofType: @ "txt"]; // 2. obtain NSData * data = [NSData dataWithContentsOfFile: path]; // initialize the array of stored data self. dataArray = [[NSMutableArray alloc] init]; // 3. parse data NSArray * resultArray = [data objectFromJSONData]; // 4. traverse the array, retrieve the dictionary, and use KVC to assign a value to the object for (NSDictionary * dict in resultArray) {Student * stu = [[Student alloc] init]; [stu setValuesForKeysWithDictionary: dict]; [self. dataArray addObject: stu];} for (Student * stu in self. dataArray) {NSLog (@ "name = % @, gender = % @, age = % ld, holobby = % @", stu. name, stu. gender, stu. age, stu. holobby );}}

Vi. Advantages and Disadvantages of XML and JSON Data Structures

1. XML advantages and disadvantages:

  • Advantages:
  • Uniform format, compliant with standards.
  • It is easy to remotely interact with other systems, making data sharing easier.
  • Disadvantages:
  • XML file format is large, complex, and occupies bandwidth for transmission.
  • Both the server side and the client side require a lot of code to parse the XML. Both the server side and the client side make the code abnormal, complex, and difficult to maintain.
  • The XML parsing methods for different browsers on the client are inconsistent. You need to repeat a lot of code.
  • It takes resources and time for the server and client to parse XML.

2. Advantages and Disadvantages of JSON:

  • Advantages:
  • The data format is relatively simple, easy to read and write, the format is compressed, and the bandwidth usage is small.
  • This language is easy to parse.
  • Supports multiple languages, including ActionScript, C, C #, ColdFusion, JAVA, JAVAScript, Perl, PHP, Python, Ruby, and other language server-side languages for server-side parsing.
  • Because the JSON format can be used directly for the server code, it greatly simplifies the code development of the server and client, but the completed tasks remain unchanged and easy to maintain.
  • Disadvantages:
  • Without the popularity and wide application of XML format, the versatility is not as good as XML.
  • JSON format is currently in the initial stage of Web Service promotion.

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.