IOS SDK自带的NSXML框架是采用SAX模式解析的,是基于事件驱动型的,主要解析工作在NSXMLParseDelegate中完成,解析过程中遇到开始标签、结束标签、文档开始、文档结束和字符串时触发Delegate中的方法完成解析,这种方式使用起来还是比较麻烦的。在实际工作中,我们可以选用一个比较简单易用的第三方框架TBXML,其下载地址为:https://github.com/71squared/tbxml
下载完成解压后,我们只需要将TBXML-Headers和TBXML-Code文件夹添加到工程中,并在工程头文件xxx-Prefix.pch中添加宏定义:#define ARC_ENABLED
由于TBXML依赖于libz.dylib库,还需在工程的Framework中添加这个库,添加完,可以编译试运行一下看是否出错,没错则继续。
例如,我们要解析以下xml文件:
<?xml version="1.0" encoding="UTF-8"?> <Notes> <Note id="1"> <CDate>2012-12-21</CDate> <Content>早上8点钟到公司</Content> <UserID>tony</UserID> </Note> <Note id="2"> <CDate>2012-12-22</CDate> <Content>发布iOSBook1</Content> <UserID>tony</UserID> </Note> <Note id="3"> <CDate>2012-12-23</CDate> <Content>发布iOSBook2</Content> <UserID>tony</UserID> </Note> <Note id="4"> <CDate>2012-12-24</CDate> <Content>发布iOSBook3</Content> <UserID>tony</UserID> </Note> <Note id="5"> <CDate>2012-12-25</CDate> <Content>发布2016奥运会应用iPhone版本</Content> <UserID>tony</UserID> </Note> <Note id="6"> <CDate>2012-12-26</CDate> <Content>发布2016奥运会应用iPad版本</Content> <UserID>tony</UserID> </Note> </Notes>
创建一个NotesTBXMLParser类来解析XML文档,具体实现代码如下:
// NotesTBXMLParser.h #import "TBXML.h" @interface NotesTBXMLParser : NSObject //解析出的数据内部是字典类型 @property (strong,nonatomic) NSMutableArray *notes; //开始解析 -(void)start; @end
#import "NotesTBXMLParser.h" @implementation NotesTBXMLParser //开始解析 -(void)start { _notes = [NSMutableArray new]; TBXML* tbxml = [[TBXML alloc] initWithXMLFile:@"Notes.xml" error:nil]; //从文件构造TBXML对象
TBXMLElement * root = tbxml.rootXMLElement;//获取文档的根元素对象 // if root element is valid if (root) { TBXMLElement * noteElement = [TBXML childElementNamed:@"Note" parentElement:root]; while ( noteElement != nil) { NSMutableDictionary *dict = [NSMutableDictionary new];
TBXMLElement *CDateElement = [TBXML childElementNamed:@"CDate" parentElement:noteElement]; if ( CDateElement != nil) { NSString *CDate = [TBXML textForElement:CDateElement]; [dict setValue:CDate forKey:@"CDate"]; }
TBXMLElement *ContentElement = [TBXML childElementNamed:@"Content" parentElement:noteElement]; if ( ContentElement != nil) { NSString *Content = [TBXML textForElement:ContentElement]; [dict setValue:Content forKey:@"Content"]; } TBXMLElement *UserIDElement = [TBXML childElementNamed:@"UserID" parentElement:noteElement]; if ( UserIDElement != nil) { NSString *UserID = [TBXML textForElement:UserIDElement]; [dict setValue:UserID forKey:@"UserID"]; } //获得ID属性 NSString *_id = [TBXML valueOfAttributeNamed:@"id" forElement:noteElement error:nil]; [dict setValue:_id forKey:@"id"]; [_notes addObject:dict]; noteElement = [TBXML nextSiblingNamed:@"Note" searchFromElement:noteElement]; } } NSLog(@"解析完成..."); [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadViewNotification" object:self.notes userInfo:nil]; self.notes = nil; }
@end