您可以尝试实现 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 类,然后为 Hotel、Beach 和用于存储这些对象的数组创建 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 *)url; 解析所需的 XML 并检索对象。
希望这可以帮助。