Parsing XML for iOS development

Source: Internet
Author: User

XML parsing can mainly use CDATA,LIBXML2 and Nsxmlparser, and the following examples are given for each method:

1.CDataXML:

1.1. Create a Fkbook class

#import <Foundation/Foundation.h> @interface Fkbook:nsobject@property (nonatomic, assign) Nsinteger bookid;@ Property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *author; @property (nonatomic, copy) NSS Tring *remark; @end

#import "FKBook.h"

@implementation Fkbook
@synthesize Bookid,title,author,remark;
@end
1.2. Create a Fkbooksparser class

#import <Foundation/Foundation.h> @interface fkbooksparser:nsobject-(nsarray*) Parsexml: (nsstring*) xmlname;@ End

#import "FKBooksParser.h"#import"FKBook.h"#import"GDataXMLNode.h"@implementation fkbooksparser-(nsarray*) Parsexml: (nsstring*) xmlname{//Use the NSBundle object to obtain the path to the XML document that needs to be parsedNSString *path = [[NSBundle mainbundle] pathforresource:xmlnameoftype:@ "XML"];//Using the Nsfilehandle object to obtain a file based on the file pathNsfilehandle *file = [Nsfilehandle Filehandleforreadingatpath:path];//Read file contents return NSData ObjectNSData *data = [File Readdatatoendoffile];//Initialize Gdataxmldocument object According to NSData objectGdataxmldocument *doc = [[Gdataxmldocument alloc] initwithdata:dataoptions:0 Error:nil];//If you need to initialize the Gdataxmldocument object based on an XML string, call the following code//gdataxmldocument *doc = [[Gdataxmldocument alloc] Initwithxmlstring:xmlstr//options:0 Error:nil];//Get root element, i.e. get <books.../> elementGdataxmlelement *rootelement = [Doc rootelement];//Get rootelement all <book.../> elements, return all <book.../> elements of the collectionNsarray *bookelements = [RootElement elementsforname:@] Book"];//Initialize a mutable array to store the contents of all <book.../> elements that will be fetchedNsmutablearray *books = [[Nsmutablearray alloc] init];//Loop through each <book.../> element for(Gdataxmlelement *bookelement in bookelements) {//Initialize the Fkbook objectFkbook *book = [[Fkbook alloc] init];//Get id attribute value, and turn into shapingNsinteger BookID = [[[Bookelement attributeforname:@]ID"]stringvalue] integervalue];//Get Title,author,remark element contentNSString *title = [[[Bookelement elementsforname:@]title"]objectatindex:0] stringvalue]; NSString *author = [[[Bookelement elementsforname:@]author"]objectatindex:0] stringvalue]; NSString *remark = [[[Bookelement elementsforname:@]Remark"]objectatindex:0] stringvalue];//Store the acquired property values and element contents into the properties of the Fkbook objectBook.bookid = Bookid;book.title = Title;book.author = Author;book.remark = remark;//Add each book object to a mutable array[Books Addobject:book];}//Returns a copy of the books collectionreturn[Books copy];} @end


1.3. Create Fkviewcontroller:uitableviewcontroller

#import "FKViewController.h"#import"FKBooksParser.h"#import"FKBook.h"@implementation fkviewcontrollernsarray* books;-(void) viewdidload{[Super Viewdidload];//Get Fkbooksparser Instance Objectfkbooksparser* booksparser = [[Fkbooksparser alloc] init];//Parse XML document, get parsed Nsarray collectionBooks =[booksparser parsexml:@ "Books"];} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{the///books property contains the number of elements, and the number of table rows is displayed here. returnBooks.count;} -(UITableViewCell *) TableView: (UITableView *) Tableviewcellforrowatindexpath: (Nsindexpath *) indexpath{//Get reusable cellsuitableviewcell* cell = [TableView dequeuereusablecellwithidentifier:@]Bookcell[Forindexpath:indexpath];//Remove 3 Uilabel controls from a reusable cell according to taguilabel* Titlelabel = (uilabel*) [cell viewwithtag:1]; uilabel* Authorlabel = (uilabel*) [cell viewwithtag:2]; uilabel* Remarklabel = (uilabel*) [cell viewwithtag:3]; fkbook* book = [Books ObjectAtIndex:indexPath.row];//Set text for 3 UilabelTitlelabel.text = Book.title;authorlabel.text = Book.author;remarklabel.text = Book.remark;returnCell;} @end


2.libxml2xml:

2.1. Create Fkbook class #import <Foundation/Foundation.h> @interface fkbook:nsobject@property (nonatomic, assign) Nsinteger BookID; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *author; @property (non Atomic, copy) NSString *remark, @end #import "FKBook.h"@implementation fkbook@synthesize Bookid,title,author,remark; @end2.2. Create Fkbooksparser class #import <foundation/ Foundation.h> @interface fkbooksparser:nsobject-(nsarray*) Parsexml: (nsstring*) xmlname; @end #import "FKBooksParser.h"#import"FKBook.h"#import"GDataXMLNode.h"@implementation fkbooksparser-(nsarray*) Parsexml: (nsstring*) xmlname{//Use the NSBundle object to obtain the path to the XML document that needs to be parsedNSString *path = [[NSBundle mainbundle] pathforresource:xmlnameoftype:@ "XML"];//Using the Nsfilehandle object to obtain a file based on the file pathNsfilehandle *file = [Nsfilehandle Filehandleforreadingatpath:path];//Read file contents return NSData ObjectNSData *data = [File Readdatatoendoffile];//Initialize Gdataxmldocument object According to NSData objectGdataxmldocument *doc = [[Gdataxmldocument alloc] initwithdata:dataoptions:0 Error:nil];//If you need to initialize the Gdataxmldocument object based on an XML string, call the following code//gdataxmldocument *doc = [[Gdataxmldocument alloc] Initwithxmlstring:xmlstr//options:0 Error:nil];//Get root element, i.e. get <books.../> elementGdataxmlelement *rootelement = [Doc rootelement];//Get rootelement all <book.../> elements, return all <book.../> elements of the collectionNsarray *bookelements = [RootElement elementsforname:@] Book"];//Initialize a mutable array to store the contents of all <book.../> elements that will be fetchedNsmutablearray *books = [[Nsmutablearray alloc] init];//Loop through each <book.../> element for(Gdataxmlelement *bookelement in bookelements) {//Initialize the Fkbook objectFkbook *book = [[Fkbook alloc] init];//Get id attribute value, and turn into shapingNsinteger BookID = [[[Bookelement attributeforname:@]ID"]stringvalue] integervalue];//Get Title,author,remark element contentNSString *title = [[[Bookelement elementsforname:@]title"]objectatindex:0] stringvalue]; NSString *author = [[[Bookelement elementsforname:@]author"]objectatindex:0] stringvalue]; NSString *remark = [[[Bookelement elementsforname:@]Remark"]objectatindex:0] stringvalue];//Store the acquired property values and element contents into the properties of the Fkbook objectBook.bookid = Bookid;book.title = Title;book.author = Author;book.remark = remark;//Add each book object to a mutable array[Books Addobject:book];}//Returns a copy of the books collectionreturn[Books copy];} @end

2.3 Creating Fkviewcontroller:uitableviewcontroller

#import "FKViewController.h"#import"FKBooksParser.h"#import"FKBook.h"@implementation fkviewcontrollerfkbooksparser* booksparser;-(void) viewdidload{[Super Viewdidload];//Get Fkbooksparser Instance ObjectBooksparser = [[Fkbooksparser alloc] init];//Parse XML document[Booksparser readxml:@]Books"];} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{///Booksparser The Books property contains the number of elements, and the number of table rows is displayed here. returnBooksParser.books.count;} -(UITableViewCell *) TableView: (UITableView *) Tableviewcellforrowatindexpath: (Nsindexpath *) indexpath{//Get reusable cellsuitableviewcell* cell = [TableView dequeuereusablecellwithidentifier:@]Bookcell[Forindexpath:indexpath];//Remove 3 Uilabel controls from a reusable cell according to taguilabel* Titlelabel = (uilabel*) [cell viewwithtag:1]; uilabel* Authorlabel = (uilabel*) [cell viewwithtag:2]; uilabel* Remarklabel = (uilabel*) [cell viewwithtag:3]; fkbook* book = [Booksparser.books ObjectAtIndex:indexPath.row];//Set text for 3 UilabelTitlelabel.text = Book.title;authorlabel.text = Book.author;remarklabel.text = Book.remark; NSLog (@ "---%d", Book.bookid);returnCell;} @end

3.NSXMLParser

#import <Foundation/Foundation.h> @interface Fkxmlpraserdelegate:nsobject <NSXMLParserDelegate>//Define a Nsmutablearray collection to hold the data obtained from parsing an XML document@property (nonatomic, strong) Nsmutablearray *books; @end #import "FKXMLPraserDelegate.h"#import"FKBook.h"@implementation Fkxmlpraserdelegate//Define a Fkbook object to hold the data in the <book> element being parsedfkbook* Book; nsstring* Currentelementvalue;//Triggers the method when an element is started to be processed-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *) Elementnamenamespaceuri: (NSString *) NamespaceURI QualifiedName: (NSString *) Qnameattributes: (Nsdictionary *) Attributedict{nslog (@ "start processing element%@", elementname);if([ElementName isequaltostring:@]Books"]){if the root element is being processed, the Nsmutablearray collection that stores the parsing result is initialized hereSelf.books = [[Nsmutablearray alloc] init];}//If the <book.../> element is being processedElse if([ElementName isequaltostring:@] Book"]){//Initialize the Fkbook objectbook = [[Fkbook alloc] init];//Read the value of the attribute ID of the <book.../> element from the AttributedictBook.bookid = [[Attributedict objectforkey:@]ID"] integervalue];}}//Triggers the method when the string content is started processing-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) String{nslog (@ "working with string content:%@", string);//If the current string value is not nil, save the value of the element that is currently being processedif(string) {currentelementvalue = string;}}//Triggers the method when an element is processed at the end-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) Elementnamenamespaceuri: (NSString *) NamespaceURI QualifiedName: (NSString *) qname{//If the processing root element ends, indicates that the XML document processing is complete. if([ElementName isequaltostring:@]Books"]){return;}//If the processing <book.../> element ends, the encapsulated Fkbook object is added to the Nsmutablearray collectionElse if([ElementName isequaltostring:@] Book"]) {[Self.books Addobject:book];book = nil;}Else{//If neither process <books.../> element nor process <book.../> element ,//Use the KVC method to assign a value to the properties of the current Fkbook object[book Setvalue:currentelementvalue forkey:elementname];currentelementvalue = Nil;}} @end

Parsing XML for iOS development

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.