1.首先引用委托
<NSXMLParserDelegate>
并声明
NSXMLParser变量。
2.开始读取xml内容进行解析
- (IBAction)DoParser:(id)sender { self.xmlString=@"<?xml version="1.0" encoding="UTF-8"?><root><person id="1"><firstname>尤1</firstname><secondname>吴1</secondname></person><person id="2"><firstname>尤2</firstname><secondname>吴2</secondname></person></root>"; NSData *xmldata=[[NSData alloc]init]; xmldata=[self.xmlString dataUsingEncoding:NSUTF8StringEncoding]; self.xmlParser=[[NSXMLParser alloc]initWithData:xmldata]; [self.xmlParser setDelegate:self]; [self.xmlParser parse]; }
//开始解析 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { NSLog(@"开始处理元素:%@",elementName);
//可获取元素属性 if ([elementName isEqualToString:@"person"]) { NSLog(@"attributes:%@",[attributeDict objectForKey:@"id"]); } }
//完成解析 - (void)parserDidEndDocument:(NSXMLParser *)parser{ if (self.soapResults) { self.soapResults=nil; } }
//元素内的内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (string) { self.soapResults=string; } }
//结束该元素解析后的操作 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"person"]) { //NSLog(@"%@",[NSString stringWithFormat:@"%@",self.soapResults ]); } NSLog(@"%@:%@",elementName,self.soapResults); } //报错时的操作 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSLog(@"%@",parseError); if (self.soapResults) { self.soapResults=nil; } }