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 parsed nsstring *path = [[NSBundle mainbundle] Pathforresource: xmlnameoftype:@ "xml"];//uses Nsfilehandle objects to obtain files based on file path Nsfilehandle *file = [Nsfilehandle filehandleforreadingatpath: path];//Read file Contents return NSData object NSData *data = [File readdatatoendoffile];// Initializes the Gdataxmldocument object according to the NSData object gdataxmldocument *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];//Gets the root element, which is the get <books.../> element gdataxmlelement *rootelement = [doc rootelement];//gets all the <book.../> elements under RootElement, returns a collection of all <book.../> elements nsarray *bookelements = [rootelement elementsforname:@ "book"];//Initializes a mutable array that stores the contents of all <book.../> elements to be fetched nsmutablearray *books = [Nsmutablearray Alloc] init];//loops through each of the <book../> element for (gdataxmlelement *bookelement in bookelements) {//Initialize Fkbook object Fkbook *book = [[Fkbook alloc] init];//Get id attribute value, and turn into shaping nsinteger BookID = [[[Bookelement attributeforname:@ ' id ']stringvalue] integervalue];//get Title,author, Remark element content NSString *title = [[bookelement elementsforname:@ ' title ']objectatindex:0] stringvalue]; NSString *author = [[[Bookelement elementsforname:@ "author"]objectatindex:0] stringvalue]; NSString *remark = [[[Bookelement elementsforname:@ "remark"]objectatindex:0] stringvalue];// Stores the obtained property values and element contents into the properties of the Fkbook object book.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 collection return [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 object fkbooksparser* booksparser = [[Fkbooksparser allo C] init];//parse the XML document to get the parsed Nsarray collection books =[booksparser parsexml:@ "books"];} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{//Books property contains the number of elements, The number of table rows is displayed here. return books.count;} -(UITableViewCell *) TableView: (UITableView *) Tableviewcellforrowatindexpath: (Nsindexpath *) indexpath{// Get reusable cells uitableviewcell* cell = [TableView dequeuereusablecellwithidentifier:@ "Bookcell" forindexpath:indexpath];/ /Remove 3 UILabel controls from a reusable cell according to tag uilabel* 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 Uilabel titlelabel.text = Book.title;authorlabel.text = book.author;remarklabel.text = Book.remark;return cell;} @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. Creating 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 NSBundle object to obtain the path to the XML document that needs to be parsed nsstring *path = [[NSBundle Mainbundle] pathforresource:xmlnameoftype:@ "xml"];//use Nsfilehandle object to get to file by file path Nsfilehandle *file = [ Nsfilehandle filehandleforreadingatpath:path];//Read File contents return NSData object NSData *data = [File readdatatoendoffile];// Initialize Gdataxmldocument object According to NSData object gdataxmldocument *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];//Gets the root element, which is the get <books.../> element gdataxmlelement * RootElement = [Doc rootelement];//gets rootelement under all <book.../> elements, returns all <book.../> elements of the collection Nsarray * bookelements = [rootelement elementsforname:@ "book"];//Initializes a mutable array to store the contents of all <book.../> elements that will be acquired Nsmutablearray * Books = [[Nsmutablearray alloc] init];//loops through each <book.../> element for (gdataxmlelement *bookelement in bookelements) {// Initializes the Fkbook object Fkbook *book = [[Fkbook alloc] init];//gets the id attribute value, and turns into shaping nsinteger BookID = [[[Bookelement attributeforname:@] Id "]stringvalue] integervalue];//get title,author,remark element content nsstring *title = [[[Bookelement elementsforname:@ ' title '] OBJECTATINDEX:0] stringvalue]; NSString *author = [[[Bookelement elementsforname:@ "author"]objectatindex:0] stringvalue]; NSString *remark = [[[Bookelement elementsforname:@ "remark"]objectatindex:0] stringvalue];Stores the obtained property values and element contents into the properties of the Fkbook object book.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 collection return [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 Object booksparser = [[Fkbooksparser alloc] init];//parse XML document [Booksparser readxml:@ "Books"];} -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{// The books property of the Booksparser contains the number of elements, and the number of table rows is displayed here. return booksParser.books.count;} -(UITableViewCell *) TableView: (UITableView *) Tableviewcellforrowatindexpath: (Nsindexpath *) indexpath{// Get reusable cells uitableviewcell* cell = [TableView dequeuereusablecellwithidentifier:@ "Bookcell" forindexpath:indexpath];/ /Remove 3 UILabel controls from a reusable cell according to tag uilabel* 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 Titlelabel.text = Book.title for 3 Uilabel; Authorlabel.text = Book.author;remarKlabel.text = Book.remark; NSLog (@ "---%d", book.bookid); return cell;} @end
3.NSXMLParser
#import <Foundation/Foundation.h> @interface Fkxmlpraserdelegate:nsobject <nsxmlparserdelegate>// Defines a Nsmutablearray collection to hold data @property (nonatomic, strong) Nsmutablearray *books for parsing XML documents; @end #import " FKXMLPraserDelegate.h "#import" FKBook.h "@implementation fkxmlpraserdelegate//define a Fkbook object to hold the <book> that is being parsed The data in the element fkbook* book; Nsstring* currentelementvalue;//triggers the method when it starts processing an element-(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, This is where you initialize the Nsmutablearray collection of the storage parsing results self.books = [[Nsmutablearray alloc] init];} If you are working with the <book.../> element else if ([ElementName isequaltostring:@ "book"]) {//Initialize Fkbook object book = [[Fkbook alloc] init];/ /Read the value of the attribute ID of the <book.../> element from attributedict book.bookid = [[attributedict objectforkey:@ "id"] integervalue];}} This method is triggered when the string content is started-(void) parser:(Nsxmlparser *) Parser foundcharacters: (NSString *) String{nslog (@ "Processing string contents:%@", string);//If the current string value is not nil, Saves the value of the element that is currently being processed if (string) {Currentelementvalue = string;}} This method is triggered when processing an element ends-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) Elementnamenamespaceuri: (NSString * ) NamespaceURI QualifiedName: (NSString *) qname{//if the processing root element ends, it 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 collection in the Else if ([ElementName isequaltostring:@ "book"]) {[ Self.books Addobject:book];book = nil;} else{//if neither the <books.../> element nor the <book.../> element is processed,//the property of the current Fkbook object is assigned a value using the KVC method [book SetValue: Currentelementvalue forkey:elementname];currentelementvalue = nil;}} @end
iOS Development XML parsing