iOS Development 2-parsing XML data with sax

Source: Internet
Author: User

XML data structure and parsing 1.1 XML Data Structurexml  is an abbreviation for Extensible Markup Language (Extensible markup language), where the   tag (Markup) is a critical part. You can create content and then mark it with qualifying tags, making each word, phrase, or block a recognizable, categorical piece of information. Created files, or document instances   consist of elements (tags) and content. Elements help to better understand the document when it is read from the printout or processed in electronic form. The more descriptive the element, the easier it is to identify the parts of the document. Since the advent of tags, tagged content has an advantage, that is, when a computer system is missing, it is still possible to print out data by means of a markup understanding. What is  xml? xml  refers to Extensible Markup Language (Extensible markup language) xml  is a markup language, very similar to  HTMLXML  is designed to transfer data, Instead of displaying the data, the xml  tag is not pre-defined. You need to define your own labels. xml  is designed to be self-descriptive. There is no act of  XMLXML  is not the act. Maybe it's a little hard to understand, but  XML  won't do anything. xml  is designed to structure, store, and transmit information. The following is a  John  write to  George  notes, stored as  XML:<note><to>George</to><from> John</from> 1.2 parsing XML using saxSax is the abbreviation of simple API for XML, which does not need to be read into the entire document when parsing XML, and the process of reading the document is the parsing process of sax. 1.2.1 First format (no write attribute)Data_xml1.txt<messages>

<message>
<sender> Xiao Ming </sender>
<receiver> Little Red </receiver>
<content> See you at the school yard today </content>
<date>2015 October 19 </date>
</message>

<message>
<sender> Floret </sender>
<receiver> Xiao Wang </receiver>
<content> See you tomorrow at noon in the park </content>
<date>2015 October 19 </date>
</message>

</messages>
//Parsing XML//1.SAX Progressive Parsing (System-provided) data is used in large numbers.//1.1 Providing a file path string//Get file 1NSString * Filepath1=[[nsbundle Mainbundle]pathforresource:@"DATA_XML1"OfType:@"txt"]; NSData* data1=[NSData datawithcontentsoffile:filepath1]; //1.2XML ParserNsxmlparser *parser1=[[Nsxmlparser alloc]initwithdata:data1]; //Set up proxyParser1.Delegate=Self ; //1.3 Starting the parser[Parser1 parse]; //Show parsed documents     for(Message *minchSelf.dataarray) {NSLog (@"sender:%@", M.sender); NSLog (@"receiver:%@", M.receiver); NSLog (@"content:%@", m.content); NSLog (@"date:%@", m.date); }#pragmaMark--The first file format//Start parsing documents-(void) Parserdidstartdocument: (Nsxmlparser *) parser{NSLog (@"First file format"); NSLog (@"Start parsing documents"); Self.dataarray=[nsmutablearray array];//initializing an array}//parse to start tag-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary<nsstring *,nsstring *> *) attributedict{NSLog (@"start tag elementname=%@", elementname); //Judging tags, creating objects    if([ElementName isequaltostring:@"message"]) {        //message was detected creating a Save information objectMessage * m=[[Message alloc]init]; //depositing Arrays[Self.dataarray addobject:m]; } self.appendstring=[nsmutablestringstring];//Initialize the stitching string//start with a number, read two times-so you need to stitch the string//2015-10-19 11:10:46.411 Content string=2015//2015-10-19 11:10:46.411 content string= October 19}//Parse to content label-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *)string{NSLog (@"content string=%@",string); //Stitching Strings[Self.appendstring appendString:string];}//resolve to end tag-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qname{NSLog (@"end Tag elementname=%@", elementname); //Deposit ObjectMessage *m=self.dataarray.lastobject;//at the end of the line//stored value-this way one of the assignments, if the label too much is inconvenient//if ([@ "sender" Isequaltostring:elementname]) {m.sender=self.appendstring;}//if ([@ "receiver" Isequaltostring:elementname]) {m.receiver=self.appendstring;}//if ([@ "date" Isequaltostring:elementname]) {m.date=self.appendstring;}//if ([@ "content" Isequaltostring:elementname]) {m.content=self.appendstring;} //It is convenient to use KVC to save value[M setValue:self.appendString forkey:elementname];}//Parse to Error-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror{NSLog (@"XML error!");}//End Parsing Document-(void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@"End Parsing Document");}

1.2.2 second format (written in attribute)

Data_xml2.txt<messages>

<message sender= "Sam" receiver= "Jack" content= "School 4PM" date= "2015-10-19" >
</message>

<message sender= "Bob" receiver= "Kate" content= "School 7PM" date= "October 19, 2015" >
</message>

</messages>
//Parsing XML//1.SAX Progressive Parsing (System-provided) data is used in large numbers.//1.1 Providing a file path string//Get file 2NSString * Filepath2=[[nsbundle Mainbundle]pathforresource:@"DATA_XML2"OfType:@"txt"]; NSData* data2=[NSData Datawithcontentsoffile:filepath2]; //1.2XML ParserNsxmlparser*parser2=[[Nsxmlparser alloc]initwithdata:data2]; //Set up proxyParser2.Delegate=Self ; //1.3 Starting the parser[Parser2 parse]; //Show parsed documents     for(Message *minchSelf.dataarray) {NSLog (@"sender:%@", M.sender); NSLog (@"receiver:%@", M.receiver); NSLog (@"content:%@", m.content); NSLog (@"date:%@", m.date); }#pragmaMark--The second file format//Second file format-(void) Parserdidstartdocument: (Nsxmlparser *) parser{Self.dataarray=[Nsmutablearray array]; NSLog (@"Start parsing");}-(void) Parserdidenddocument: (Nsxmlparser *) parser{NSLog (@"End parsing");}-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) QName attributes: (nsdictionary<nsstring *,nsstring *> *) attributedict{//NSLog (@ "attributedict=%@", attributedict);        if([ElementName isequaltostring:@"message"]) {Message*m=[[Message alloc]init];        [M setvaluesforkeyswithdictionary:attributedict];    [Self.dataarray addobject:m]; }    }

Code Download (Xcode7.0.1)

iOS Development 2-parsing XML data with sax

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.