你可以嘗試實現NSXMLParserDelegate然後寫你的邏輯在
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:
(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary
*)attributeDict
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:
(NSString *)namespaceURI qualifiedName:(NSString *)qName
示例代碼: -
用於存儲這些對象創建XMLParser的類,然後對酒店,海灘bean類和數組。
XMLParser.h
#import <Foundation/Foundation.h>
@interface XMLParser : NSObject <NSXMLParserDelegate>
@property (strong, readonly) NSMutableArray *yourObjects;
-(id) parseXML:(NSString *)url;
@end
XMLParser.m
#import "XMLParser.h"
#import "YourObject.h"
@implementation XMLParser
@synthesize yourObjects =_yourObjects;
NSMutableString *currentNode;
NSXMLParser *parser;
YourObject *YourObject;
-(id) parseXML:(NSString *)url
{
_yourObjects = [[NSMutableArray alloc]init];
NSURL *nsURL = [NSURL URLWithString:url];
NSData *data = [[NSData alloc] initWithContentsOfURL:nsURL];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNode = (NSMutableString *) [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:
(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary
*)attributeDict
{
if ([elementName isEqualToString:@"hotel"])
{
yourObject = [YourObject alloc]; //eg:- Hotel
//any logic that you want to include.....
}
if ([elementName isEqualToString:@"beach"])
{
yourObject = [YourObject alloc]; //eg:- beach
//any logic that you want to include.....
}
}
@end
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:
(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"status"])
{
[self.yourObjects addObject:yourObject];
yourObject = nil;
currentNode = nil;
}
}
電話 - (ID)parseXML:(的NSString *)網址;解析所需的XML並檢索對象。
希望這會有所幫助。