這篇文章使用了NSXMLParser。
NSXMLParser *parser=[[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]]; // NSXMLParser *parser=[[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml"]]; [parser setDelegate:self];//設定NSXMLParser對象的解析方法代理 [parser setShouldProcessNamespaces:NO]; [parser parse];//開始解析
2、委託方法
//發現元素開始符的處理函數 (即報告元素的開始以及元素的屬性) - (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:parserErrorOccured
執行[parser parse]後會依序執行:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { NSLog(@"xml_parser start %@ ",elementName); if ( [elementName isEqualToString:@"person"] ) { NSLog(@"xml_parser person "); if(personNameArrary==nil){ personNameArrary=[[NSMutableArray alloc] init]; } } if(itemValue!=nil){ itemValue=nil; } itemValue=[[NSMutableString alloc] init]; if ( [elementName isEqualToString:@"phone"] ) { NSString *atr=[attributeDict valueForKey:@"type"]; NSLog(@"xml_parser phone type: %@",atr); }}- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { NSLog(@"xml_parser value:%@",string); [itemValue appendString:string];}- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSLog(@"xml_parser end %@ ",elementName); if ( [elementName isEqualToString:@"firstName"] ) { [personNameArrary addObject:itemValue]; } if ( [elementName isEqualToString:@"person"] ) { NSLog(@"xml_parser person end"); } }
NSXMLParser DEMO 下載
@張興業TBOW
http://www.cnblogs.com/dotey/archive/2011/05/11/2042000.html
https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html#//apple_ref/doc/uid/20002265-BCIJFGJI
http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project#