1.创建NSXMLParser
要使用NSXMLParser要先创建它,设置各种属性,主要用到以下几个方法:
initWithContentsOfURL通过NSURL创建解析器
initWithData通过NSData创建解析器
setDelegate为解析器定义委托
parse运行解析器
NSData * xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Student" ofType:@"txt"]]; NSXMLParser * xmlParser = [[NSXMLParser alloc]initWithData:xmlData]; xmlParser.delegate = self; [xmlParser parse]; [xmlParser release];
// 开始解析 - (void)parserDidStartDocument:(NSXMLParser *)parser{ NSLOG_FUNCTION; } //解析到某个起始标签 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"%@",elementName); NSLOG_FUNCTION; } //解析到节点的值 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLOG_FUNCTION; NSLog(@"%@",string); } //解析到某个结束标签 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ NSLog(@"%@",elementName); NSLOG_FUNCTION; } //结束解析 - (void)parserDidEndDocument:(NSXMLParser *)parser{ NSLOG_FUNCTION; }