iOS Development Web Chapter I: Data Interchange Format

Source: Internet
Author: User

Network communication is the most commonly used data communication format is XML and JSON, each has its own benefits, anyway, this format, we are often used in the process of development, now in these two formats to take notes, the following content does not do a detailed analysis, Work with XML and JSON content only on how to apply various read and write tools

Xml

Parsing an XML file now has two main types, sax and Dom

    • Sax-based on time-event-driven, meaning that the process of reading, is from the top down to read the XML file, when the node encountered, trigger the corresponding event, using the faster, the disadvantage is that the file content can not be modified
    • dom-is loaded in a tree form and stored in memory after loading, so if the file is large, the read time will be longer, but the file can be modified

The iOS SDK provides two frameworks, and some third-party frameworks, where only 2 types of nsxml and Tbxml are introduced.

    • nsxml-It is written in object-c language and supports only the SAX parsing framework
    • Libxml2
    • Tbxml-uses the parsing framework of the DOM (it is said to have time to test it soon)
    • Touchxml
    • Kissxml
    • TinyXML
    • Gdataxml

Now that there is an XML file that is now read in Nsxml mode, we have also written a class for reading and writing XML

The first one is about Nsxml.

Nodetext.xml

<?XML version= "1.0" encoding= "UTF-8"?><Notes>    <NoteID= "1">      <Name>8 points?? To????</Name>      <UserID>Tony</UserID>    </Note>    <NoteID= "1">      <Name>8 points?? To????</Name>      <UserID>Tony</UserID>    </Note></Notes>        

The following class is used for reading and writing XML, must use the delegate nsxmlparserdelegate, here are two methods, one is the first Initwithurl: need to provide file address, another method is parser, The method is to start parsing the XML file's entry

XMLReader.h file

#import <Foundation/Foundation.h>@interface xmlreader:nsobject<nsxmlparserdelegate >*dict; -(ID) Initwithurl: (Nsurl *) URL; -(void) parser; @end

The specific implementation is as follows

Xmlreader.m,nsxmlparserdelegate delegate contains a number of methods can be, here mainly the following several methods of replication

  • -(void) Parserdidstartdocument: (nsxmlparser *) parser

    • Called when the document starts, read only once
  • -(void) Parserdidenddocument: (nsxmlparser *) parser

    • Called when the document parsing is finished, read only once
  • -(void Nsxmlparser *) parser didstartelement: (nsstring *) elementname   namespaceuri: ( Nsstring namespaceuri  qualifiedname: ( nsstring *) qualifiedname  attributes: (nsdictionary *) attributedict

  • -(void Nsxmlparser *) parser didendelement: (nsstring *) elementname NamespaceURI: (nsstring *) NamespaceURI QualifiedName: (NSString *) qName

    • < Span class= "S3" > call when the node ends
  • -(void) Parser: (nsxmlparser *) Parser foundcharacters: (nsstring *) string

    • Called when the string inside the node is read.
@interfaceXmlReader () @property (nonatomic) Nsurl*URL;@end@implementationXmlReader-(ID) Initwithurl: (Nsurl *) url{ Self=[Super Init]; if(self) {Self.url=URL; }    returnSelf ;}-(void) parser{Nsxmlparser*parser =[[Nsxmlparser Alloc]initwithcontentsofurl:self.url]; Parser.Delegate=Self ; BOOL b=[parser parse];}- (void) Parserdidstartdocument: (Nsxmlparser *) parser{self.dict=[[Nsmutabledictionary alloc]init];}//sent when the parser begins parsing of the document.- (void) Parserdidenddocument: (Nsxmlparser *) parser{}- (void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString*) NamespaceURI qualifiedname: (NSString*) QualifiedName attributes: (nsdictionary*) attributedict{NSLog (@"%@", elementname);}-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *)string{NSLog (@"%@",string);}-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qname{NSLog (@"%@", elementname);}@end

The second is about Tbxml.

This is a third-party to provide the reading method, so need to import code engineering, can go to https://github.com/71squared/TBXML download source, download the zip package or hub sync download, I use the download zip package, download good after decompression, Will get a lot of files, but here only need to extract TBXML.h and tbxml.m files, put them into the project, directly use can. According to some of the Internet some different experience, some because do not support the arc mechanism, and reported the wrong, Some because the project did not import Libz.dylib package and error, anyway, no package of direct import on the line, do not support arc to find the network of articles can be resolved, I have another situation here, that is, TBXML.h file import fundation package, so led to error, did not find NSObject

These are all configured so that you can use, here I wrote another class, used for reading the information XML, the code is as follows

XmlReaderTBXML.h file

#import <Foundation/Foundation.h>#import"TBXML.h"@ Interface*notes; // Start parsing method -(void) start; @end

XmlReaderTBXML.h file

#import "XmlReaderTBXML.h"@implementationXmlreadertbxml-(void) start{self.notes=[[Nsmutablearray alloc]init]; TBXML*tbxml = [[Tbxml alloc]initwithxmlfile:@"Nodetest.xml"Error:nil]; Tbxmlelement* Root =tbxml.rootxmlelement; if(Root) {tbxmlelement* Noteelement = [TBXML childelementnamed:@"Note"Parentelement:root];  while(Noteelement! =Nil) {Nsmutabledictionary*dict = [NsmutabledictionaryNew]; Tbxmlelement*cdateelement = [TBXML childelementnamed:@"CDate"Parentelement:noteelement]; if(Cdateelement! =Nil) {NSString*cdate =[TBXML textforelement:cdateelement]; [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"]; }            //id attributeNSString *_id = [TBXML valueofattributenamed:@"ID"forelement:noteelement Error:nil]; [Dict setvalue:_id Forkey:@"ID"];            [_notes addobject:dict]; Noteelement= [TBXML nextsiblingnamed:@"Note"Searchfromelement:noteelement]; }} NSLog (@"Parse Complete ..."); Self.notes=Nil;}@end

In this start method is the process of reading XML, very simple, do not introduce

Json

JSON is a lightweight data interchange format

iOS Development Web Chapter I: Data Interchange Format

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.