<UIKit/UIKit.h> @interfaceViewController :UIViewController<NSXMLParserDelegate> //解析器对象 NSXMLParser*parser; //根元素 XMLElement*rootElement; //当前的元素 XMLElement*currentElementPointer; 解析的ViewController.m
"ViewController.h""UIColor+ColorWithARGB.h"@interfaceViewController() @end @implementationViewController -(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { self= [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil]; if(self!=nil){ self.title=@"XML解析"; } returnself; } - (void)viewDidLoad { [viewDidLoad]; view.backgroundColor= [UIColorr:0xA5g:b:0x52]; NSString*xmlFilePath = [[NSBundlemainBundle]pathForResource:@"person"ofType:@"xml"]; NSData*data = [[NSDatainitWithContentsOfFile:xmlFilePath]; self.parser= [[NSXMLParserinitWithData:data]; parser.delegate=self; if([parserparse]){ NSLog(@"The XML is Parsed"); NSMutableString*str = [[NSMutableStringinit]; [strappendFormat:@"%@\n",116)">rootElement.name]; NSMutableArray*subs =subElements; for(inti =0;i < [subscount];i++){ XMLElement*personElement = [subsobjectAtIndex:i]; [str@"\tname:%@",personElement.name]; [str@",text:%@\n",116)">text]; NSArray*subPersonElements = personElement.subElements; intj =0;j < [subPersonElementscount];j++){ XMLElement*subElement = [subPersonElementsobjectAtIndex:j]; [str@"\t\tname:%@",subElement.text]; } } @"======解析结果:%@",str); }else{ @"Failed to parse the XML"); } } - (void)didReceiveMemoryWarning { [didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //文档开始 -(void)parserDidStartDocument:(NSXMLParser*)parser { rootElement=nil; currentElementPointer=nil; } //文档结束 -(void)parserDidEndDocument:(//元素开始 - (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName attributes:(NSDictionary*)attributeDict { rootElement==nil){ rootElement= [[XMLElementinit]; rootElement; }else{ XMLElement*newElement = [[init]; newElement.parent=currentElementPointer; [currentElementPointer.subElementsaddObject:newElement]; currentElementPointer= newElement; } name= elementName; attributes= attributeDict; @"name:%@",elementName); } //元素结束 - (NSXMLParser*)parser didEndElement:(NSString*)qName { parent; @"end name:%@",0)">//解析文本,会多次解析,每次只解析1000个字符,如果多月1000个就会多次进入这个方法 - (NSXMLParser*)parser foundCharacters:(NSString*)string { textlength] >0){ text= [stringByAppendingString:string]; }else{ text= [stringWithString:string]; } @"string:%@",string); } @end |