2012-05-01 95 views
0

我是iphone開發新手,我想要的是一個xml解析器,我可以綁定到對象。我搜查了很多,但我仍然需要一些幫助。比如我有以下XML結構:iphone xml綁定/解析到對象

<xml> 
    <hotels> 
    <hotel> 
     <id>1</id> 
     <name>Hotel Name</name> 
    </hotel> 
    <hotel> 
     .... 
    </hotel> 
    </hotels> 
    <beaches> 
    <beach> 
     <id>11</id> 
     <name>Beach Name</name> 
    </beach> 
    <beach> 
     .... 
    </beach> 
    </beaches> 
</xml> 

現在我的問題是...這是最好的(或者更簡單)的方式來閱讀這個XML文件並解析例如...:

  1. 現在我想要一個所有酒店的列表......所以我想解析並獲取該列表......等等。
  2. 現在我想的海灘與ID = 11等

這能很容易地在iphone做了什麼?哪種方法最好?如果你能給我例子的源代碼或其他東西,我會很感激。提前致謝。

注:我至少會支持ios 4.3或更高版本。

回答

1

你可以嘗試實現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並檢索對象。

希望這會有所幫助。