여기에서는 NSXMLParser를 사용하여 구문 분석합니다. 이는 Apple의 자체 XML 구문 분석 라이브러리입니다. http://www.php.cn/
Xcode에 xml 파일을 추가하세요.
먼저 읽어보세요
<?xml version="1.0" encoding="ISO-8859-1"?> <root> <Shop shoplocation="beijing"> <id>001</id> <name>John</name> <url>Reminder</url> <info>Don't forget the meeting!</info> </Shop> <Shop shoplocation="dongcheng"> <id>002</id> <name>Jack</name> <url>cc</url> <info>how are you!</info> </Shop> <Shop shoplocation="haidian"> <id>003</id> <name>Tom</name> <url>bb</url> <info>I am fine!</info> </Shop> </root>
다음 구문 분석:
NSString* path = [[NSBundle mainBundle] pathForResource:@"shop" ofType:@"xml"]; NSData *data = [[NSData alloc] initWithContentsOfFile:path options:(NSDataReadingMappedIfSafe) error:nil]; NSXMLParser *parser=[[NSXMLParser alloc] initWithData:tmpdata]; <span style="white-space:pre"> </span>[parser setDelegate:self]; [parser parse]; [parser release]; [self parseShopListFromResponse:data];
Shopdata의 구조는
#pragma mark NSXMLParser delegate methods - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict { self.currentTag = elementName; if ([elementName isEqualToString:@"root"]) { self.tmpList = [[NSMutableArray alloc] init]; }else if ([elementName isEqualToString:@"Shop"]) { self.tmpShop = [[ShopData alloc] init]; NSArray* array = [attributeDict allKeys]; NSString* key = [array lastObject]; NSString*s = [attributeDict objectForKey:key]; self.tmpShop.info = s; } } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (self.currentString == nil) { self.currentString = [[NSMutableString alloc] initWithString:@""]; } if ([self.currentTag isEqualToString:@"name"] || [self.currentTag isEqualToString:@"id"] || [self.currentTag isEqualToString:@"url"] || [self.currentTag isEqualToString:@"info"]) { [self.currentString appendString:string]; } } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"Shop"]) { [self.tmpList addObject:self.tmpShop]; [self.tmpShop release]; } if ([elementName isEqualToString:@"name"]) { self.tmpShop.name = [self.currentString copy]; [self.currentString setString:@""]; }else if ([elementName isEqualToString:@"id"]) { self.tmpShop._id = [self.currentString copy]; [self.currentString setString:@""]; }else if ([elementName isEqualToString:@"url"]) { self.tmpShop.url = [self.currentString copy]; [self.currentString setString:@""]; }else if ([elementName isEqualToString:@"info"]) { // self.tmpShop.info = [self.currentString copy]; // [self.currentString setString:@""]; } } - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"开始解析xml文件"); } - (void)parserDidEndDocument:(NSXMLParser *)parser { [self.tableView reloadData]; NSLog(@"解析xml文件完成"); }
위 내용은 IOS 파싱 XML 파일 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!