iOS开发网络篇之Web Service和XML数据解析

在iPhone和后台系统的通信中,,使用Web Service获取服务器数据上最常见的一种形式。

而在Web Service通信中,数据交换格式通常上使用XML数据,XML数据也是软件开发中普遍存在的一种格式,

因此XML解析也就成为项目开发中必须掌握的一些基本技能。

本文提供一个XML数据解析类SimpleXMLParser,

该类的特点上将XML数据解析成数据库记录形式,数据解析后保存在NSArray中,

其中数组的每个元素对应一条数据库记录,每条记录则是由数据库字段和值组成的NSDictionary。

1、接口定义

@interface SimpleXMLParser : NSObject{NSString *currentPropertyName;NSMutableString *currentData;BOOL contentError;NSString *faultName;NSString *faultName2;NSMutableData *webData;NSMutableArray *theMainStack;NSMutableArray *currentDataStack;NSXMLParser *parser;NSString *recordHead;NSInteger sectionCount;BOOL beginRecord;NSMutableString *currentCharacters;NSMutableDictionary *parsedResponseDictionary;NSString *parseElementPath;}- (id)init;- (void)initData:(NSMutableData *)data;- (void)parse:(NSString*)head;- (BOOL)isContentFault;- (NSInteger)getRecordCount;- (NSDictionary*)getRecordAtIndex:(NSInteger)idx;- (NSMutableArray*)getRecordLists;

2、使用

NSMutableData *webData;SimpleXMLParser *thisParser = [[SimpleXMLParser alloc] initWithData:webData];NSString *recordHead = @"User";[thisParser parse:recordHead];

此时解析后的数据库记录保存于Parser对象的recordStack变量中,首先获取记录条数,然后遍历每条记录。

NSInteger i = 0, nResult = [thisParser getRecordCount];for(i = 0; i < nResult; i++){NSDictionary *recordDict = [thisParser getRecordAtIndex:i];NSDictionary *tempDic = [recordDict objectForKey:@"tempDic"];NSString *value = [tempDic objectForKey:@"value"];}

版权声明:本文为博主原创文章,未经博主允许不得转载。

读书破万卷,下笔如有神。

iOS开发网络篇之Web Service和XML数据解析

相关文章:

你感兴趣的文章:

标签云: