XML, JSON data structure parsing, and third-party class references in iOS

Source: Internet
Author: User
Tags closing tag

Today we talk about the content of data structure parsing: XML and JSON two kinds

XML data structure: is extended to HTML, mainly using tags on <start></start>

There are two types of parsing:

1.SAX parsing (simple API for XML). is an event-driven parsing method that parses data row by line (with protocol callback mechanism)

Nsxmlparser is an XML parsing class that comes with iOS. Parsing process is callback by Nsxmlparserdelegate protocol mode

Parsing process: Start tab----------------to value

Use the following procedure:

@interface Tableviewcontroller () <NSXMLParserDelegate>

@property (Nonatomic,retain) Nsmutablearray *datasource;

@property (Nonatomic,retain) NSString *starttag;//by property staging start tag

@end

Nsxmlparser *aparser = [[Nsxmlparser alloc] initwithdata:[nsdata datawithcontentsoffile:[[nsbundle MainBundle]              pathforresource:@ "Students" oftype:@ "xml"]]; 1. Create an Object

Aparser.delegate = self; 2. Specifying proxy objects

[Aparser parse]; 3. Start parsing

[Aparser release]; 4. Release of ownership

The main implementation of the Protocol method has the following five kinds of

-(void) Parserdidstartdocument: (Nsxmlparser *) The parser;//parser begins parsing XML text, informing the broker that the start point of the parser parsing

-(void) Parserdidenddocument: (Nsxmlparser *) The end point of the notification proxy object resolution when the parser finishes parsing parser;//

-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary *) attributedict;//when the parser gets the start tag, it calls the Protocol method to pass the value to the proxy object

-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qname;//the protocol method is called when the parser gets the closing tag to pass the value to the proxy object

-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string;//when the parser gets the data between the start and end tags of the node, it calls the protocol method to pass data to the proxy object

2.DOM parsing (Document Object model): Google's Gdataxmlnode (used by a third-party class)

Parsing requires the XML file to be read into the whole, and the XML is structured in a tree form, using the tree structure to read the relevant data

Get the entire document

Gdataxmldocument *adocument = [[Gdataxmldocument alloc] initwithxmlstring:[nsstring stringwithcontentsoffile:[[ NSBundle Mainbundle] pathforresource:@ "Students" oftype:@ "xml"] encoding:nsutf8stringencoding Error:nil] options:0 Error:nil];

Gdataxmlelement *rootelement = [adocument rootelement]; Get root Node Object

Nsarray *subelements = [rootelement elementsforname:@ "student"];//Get child node array

Get each child node object with a quick enumeration

For (Gdataxmlelement *anelement in subelements) {

Student *astudent = [[Student alloc] init]; (Student is a custom model class)

NSString *name = [[[Anelement elementsforname:@ "name"] firstobject] stringvalue];

Astudent.name = name;

NSLog (@ "%@", [[Anelement elementsforname:@ "gender"] firstobject]);

NSString *gender = [[[Anelement elementsforname:@ "gender"] firstobject] stringvalue];

Astudent.gender = gender;

int age = [[[Anelement elementsforname:@ ' age '] firstobject]stringvalue] intvalue];

Astudent.age = age;

[Self.datasource addobject:astudent];//will acquire every student object stored in the DataSource

[AStudent release];

}

JSON data structure: a lightweight format for exchanging information

JSON? The document has two structures: object, data

Object: Starting with "{", Ending with "}", is a collection of "name/value" pairs. The middle of the name and value is separated by ":". Multiple "name/value" pairs, separated by ",". Similar to the dictionary in OC.

Array: Ends with "[", "]", and the middle is the data. The data is separated by ",".

Data types in JSON: string, numeric, BOOL, object, array.

JSON parsing using the system's own Jsom serialization class

NSData *jsondata = [NSData datawithcontentsoffile:[[nsbundle mainbundle] pathforresource:@ "Students" ofType:@ "JSON"] ;

Nsmutablearray *elements = [Nsjsonserialization jsonobjectwithdata:jsondata options:nsjsonreadingmutablecontainers Error:nil];

For (nsdictionary *dict in elements)

{

Student *astudent = [[Student alloc] init];

Astudent.name = dict[@ "name"];

Astudent.age = [dict[@ "Age"] intvalue];

Astudent.gender = dict[@ "gender"];

[Self.datasource addobject:astudent];

[AStudent release];

}

Above, the JSON uses most frequently, the structure is simple, occupies the least space, the serialization analytic method concise square, but the XML document occupies the space is the JSON file twice times also many, its two kinds of parsing methods: Sax parsing is the line-by-row parsing, The previous parsing can also be completed when there is an error in the. xml file, but the method of using protocol callbacks is too complex, but the DOM does not use the protocol callback method, but the whole document is read into after parsing, once the document editing error, will not be resolved, but can locate the location of the document error

Use of third-party classes mentioned in the article:

Get Address: http://github.com

Drag the obtained class to the project and the header file import error message appears

Libxml includes require that the target Header Search Paths contain

/usr/include/libxml2

and other Linker Flags contain

-lxml2

#import <libxml/tree.h>//Import Error

Processing method:

Click ' + '

After the file is added. In Bulid settings-->search Paths-->header Search Paths Add the path/usr/include/libxml2 to the back of the two paths

XML, JSON data structure parsing, and third-party class references in iOS

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.