准備工作:
new -> file -> other -> Empty ,在 Save As: 中隨便起個名字後綴為 .xml
拷貝下面
<person> <student> <pid>1001</pid> <name>小明</name> <sex>男</sex> <age>12</age> </student> </person>
完整代碼
// // ViewController.m // XML // // Created by CC on 16/8/29. // Copyright © 2016年 CC. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSXMLParserDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self analysis]; } - (void)analysis { NSString *filename = [[NSBundle mainBundle]pathForResource:@"File.xml" ofType:nil]; NSData *data = [[NSData alloc]initWithContentsOfFile:filename]; NSXMLParser *parset = [[NSXMLParser alloc]initWithData:data]; parset.delegate = self; [parset parse]; } //文檔開始時觸發,只觸發一次 - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"parsetStart"); } //文檔出錯時觸發 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { if (parseError) { NSLog(@"parseError:%@",parseError); } } //遇到字符串開始觸發 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { NSLog(@"00000000----- %@",string); } //遇到開始標簽觸發 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict { NSLog(@"arrributeDict --- %@",attributeDict); } //遇到結束標簽觸發 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSLog(@"didEndElement ----- %@",elementName); } //遇到文檔結束時觸發 - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"DidEndDocument"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end