ios中如何解析xml文件两种方法:1.ios中已有的NSXMLParse类 2.Google的GDataXML也是基于libxml2的,因此在使用GDataXML之前,你需要先导入libxml2。这里详解ios中的nsxmlparse:NSXMLParser 实现的是sax方法解析xml文件。dom实现的原理是把整个xml文档一次性读出,放在一个树型结构里。在需要的时候,查找特定节点,然后对节点进行读或写。他的主要优势是实现简单,读写平衡;缺点是比较占内存,因为他要把整个xml文档都读入内存,文件越大,这种缺点就越明显。sax的实现方法和dom不同。他只在xml文档中查找特定条件的内容,并且只提取需要的内容。这样做占用内存小,灵活,正好满足我们的需求。他的缺点就是写,有些资料介绍了写入的方法,但是我感觉这对本例没有必要。运行NSXMLParser涉及设置、运行和响应结果。1)启动NSXMLParser要使用NSXMLParser要先创建它,设置各种属性,主要用到以下几个方法:initWithContentsOfURL 通过NSURL创建解析器initWithData 通过NSData创建解析器setDelegate 为解析器定义委托parse 运行解析器2)充当委托最重要的5个方法: //发现元素开始符的处理函数 (即报告元素的开始以及元素的属性) - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict//处理标签包含内容字符 (报告元素的所有或部分内容) - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string//发现元素结束符的处理函数,保存元素各项目数据(即报告元素的结束标记)- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName//报告解析的结束 - (void)parserDidEndDocument:(NSXMLParser *)parser//报告不可恢复的解析错误- (void)paser:parserErrorOccured1.申明了一个xml处理协议,用到NSXMLParser协议,用来具体处理我们要解析的xml文件,把需要的url取出来,存到指定的data里。 *///多线程处理类的定义,方法实现,与向主线程回传data@class AppRecord;//@protocol ParseOperationDelegate;@protocol ParseOperationDelegate- (void)didFinishParsing:(NSArray *)appList;- (void)parseErrorOccurred:(NSError *)error;@end@interface ParseOperation : NSOperation {@private id <</span>ParseOperationDelegate> delegate;//,NSXMLParserDelegate NSData *dataToParse; NSMutableArray *workingArray; AppRecord *workingEntry; NSMutableString *workingPropertyString; NSArray *elementsToParse; BOOL storingCharacterData;}- (id)initWithData:(NSData *)data delegate:(id <<span class="s13">ParseOperationDelegate>)theDelegate;@end然后完成协议的初始化函数- (id)initWithData:(NSData *)data delegate:(id <<span class="s13">ParseOperationDelegate>)theDelegate{ self = [super init]; if (self != nil) { self.dataToParse = data; self.delegate = theDelegate; self.elementsToParse = [NSArray arrayWithObjects:kIDStr, kNameStr, kImageStr, kArtistStr, nil]; } return self;}2.完成对特定标签的解析#pragma mark -#pragma mark RSS processing- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ // entry: { id (link), im:name (app name), im:image (variable height) } // if ([elementName isEqualToString:kEntryStr]){ self.workingEntry = [[[AppRecord alloc] init] autorelease]; } storingCharacterData = [elementsToParse containsObject:elementName];}3.找到具体的地址与内容,并存储- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if (self.workingEntry){ if (storingCharacterData) { NSString *trimmedString = [workingPropertyString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; [workingPropertyString setString:@""]; // clear the string for next time if ([elementName isEqualToString:kIDStr]) { self.workingEntry.appURLString = trimmedString; } else if ([elementName isEqualToString:kNameStr]) { self.workingEntry.appName = trimmedString; } else if ([elementName isEqualToString:kImageStr]) { self.workingEntry.imageURLString = trimmedString; } else if ([elementName isEqualToString:kArtistStr]) { self.workingEntry.artist = trimmedString; } } else if ([elementName isEqualToString:kEntryStr]) { [self.workingArray addObject:self.workingEntry]; self.workingEntry = nil; } } }- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ if (storingCharacterData) { [workingPropertyString appendString:string]; }}第三方解析方法:::::::::::: 简介:采用KissXML第三方程序集来实现,需要引入libxml2.dylib(另需注意运行时可能会提示“libxml/tree.h找不到“的问题, 解决办法: 在项目的 TARGETS 中选择一个目标,在右侧切换到 Build Settings 页,向下找到 Search Paths 段,其中有一个 Header Search Paths 项,将其值设为:/usr/include/libxml2)如下图: ProvinceCity.xml文件格式如下图:程序主要代码如下: #import"DDXML.h"#import"DDXMLElementAdditions.h" @implementation ViewController//解析XMLstaticNSString *kXML =@"//District//Province";- (void)viewDidLoad{ [superviewDidLoad]; NSString *path =[[NSStringalloc]initWithString:[[NSBundlemainBundle]pathForResource:@"ProvinceCity"ofType:@"xml"]]; NSData *data = [[NSDataalloc]initWithContentsOfFile:path]; [selfparsedDataFromData:dataandProvince:@"江西省"];[selfparsedDataFromData:data];[datarelease];}//取特定省份下包含所有城市-(void)parsedDataFromData:(NSData *)data andProvince:(NSString *)province{DDXMLDocument *doc = [[DDXMLDocumentalloc]initWithData:dataoptions:0error:nil]; /////解析NSArray *items = [docnodesForXPath:kXMLerror:nil]; for (DDXMLElement *objin items) { DDXMLNode *aUser = [obj attributeForName:@"Name"];//取属性Name的值 if ([aUser.stringValueisEqualToString:province]) { NSArray *CityLst = [obj elementsForName:@"City"];//取城市点点列表,保存到数组中 if(CityLst.count>0)//第二层 { for (DDXMLElement *citysin CityLst) { DDXMLNode *citynode=[citys attributeForName:@"Name"]; NSLog(@"%@",citynode.stringValue); } } } } [doc release];}//取所有省份及其下级节点,包含修改操作-(void)parsedDataFromData:(NSData *)data{DDXMLDocument *doc = [[DDXMLDocumentalloc]initWithData:dataoptions:0error:nil]; /////解析NSArray *items = [docnodesForXPath:kXMLerror:nil]; for (DDXMLElement *objin items) {DDXMLNode *aUser = [objattributeForName:@"Name"];//取属性Name的值 //[aUser setStringValue:@"haha!"];//修改属性节点的值 [objaddAttribute:[DDXMLNodeattributeWithName:@"test"stringValue:@"wzh"]];//增加一个属性节点 [objaddAttributeWithName:@"ttt"stringValue:@"343"];//再增加一个属性节点 //[obj setStringValue:@"NewNode"];//设置当前节点的值 DDXMLNode *newnode=[DDXMLNodeelementWithName:@"newNode"];//设置一个新的节点 [obj addChild:newnode];//给obj添加一个节点 DDXMLElement *newdxml = [[objelementsForName:@"newNode"]objectAtIndex:0];//访问刚刚添加的节点 [newdxmladdAttributeWithName:@"nodetwo"stringValue:@"twovalue"];//给刚添加的节点增加增的下级节点,并且下级节点再一个属性值 DDXMLNode *newnode2=[DDXMLNodeelementWithName:@"newNode2"stringValue:@"hello!"]; [newdxmladdChild:newnode2];} //保存到沙盒目录下 NSString *path =[[NSStringalloc]initWithFormat:@"%@/xmlData.xml", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]]; NSString *result=[[NSStringalloc]initWithFormat:@"%@",doc]; [resultwriteToFile:pathatomically:YESencoding:NSUTF8StringEncoding error:nil]; //[result2 writeToFile:path atomically:YES];//这种方法不行,保存后会有乱码 [result release]; [path release]; [doc release];}