2013-07-26 35 views
1

我想從網站上獲取令牌。成功驗證後,將顯示一個XML文檔。如何抓取XML元素並將其存儲? Objective C

我建立了一個連接,如下所示:

NSString *strURLQueryString = [NSString stringWithFormat:@"%@?username=%@&password=%@", kURL_LOGIN, nameString, passwordString]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:strURLQueryString] 
               cachePolicy:NSURLRequestUseProtocolCachePolicy 
              timeoutInterval:60.0]; 

爲了顯示輸出中,我使用這樣的:

unsigned char byteBuffer[[receivedData length]]; 
[receivedData getBytes:byteBuffer]; 
NSLog(@"Output: %s", (char *)byteBuffer); 

因此,一些返回的文檔的輸出被如下所示:

<status>0</status><reason>User fetched.</reason><token>9cb7396dccabe68c067521db219afb83</token> 

我已經閱讀了許多XML解析實現,但我無法實現它作爲我這並不能滿足我的需要,我無法理解其解釋的複雜性。

如果有人能給我一個關於如何去做的好建議,我將不勝感激。

+0

使用NSXMLParser。 –

+0

使用NSXMLParser。它容易理解。它有一些很容易的代表方法。所以試試看。 –

+0

使用NSXMLParser解析它 – iEinstein

回答

1
- (XMLParserViewController *) initXMLParser { 


    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

    return self; 
} 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
    attributes:(NSDictionary *)attributeDict 
{ 

    if([elementName isEqualToString:@"Books"]) { 
     appDelegate.books = [[NSMutableArray alloc] init]; 
    } 
    else if([elementName isEqualToString:@"Book"]) 
    { 

     aBook = [[Books alloc] init]; 

    } 

    NSLog(@"Processing Element: %@", elementName); 
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 

    if(!currentElementValue) 
     currentElementValue = [[NSMutableString alloc] initWithString:string]; 
    else 
     [currentElementValue appendString:string]; 

    NSLog(@"Processing Value: %@", currentElementValue); 

} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 

    if([elementName isEqualToString:@"Books"]) 
     return; 

    if([elementName isEqualToString:@"Book"]) 
    { 
     [appDelegate.books addObject:aBook];   
      aBook = nil; 
    } 
    else if([elementName isEqualToString:@"name"]) 
    { 
     aBook.name=currentElementValue; 
    } 
    else if([elementName isEqualToString:@"address"]) 
    { 
     aBook.address=currentElementValue; 
    } 
    else if([elementName isEqualToString:@"country"]) 
    { 
     aBook.country=currentElementValue; 
    }   

    currentElementValue = nil; 


    NSLog(@"%@",aBook.name); 
    NSLog(@"%@",aBook.address); 
    NSLog(@"%@",aBook.country); 
} 

試試這個,,我希望這個工程....

0

相關NSXMLParserDelegate方法:

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName //etc 
{ _inToken = [elementName isEqualToString:@"token"]; } 

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName //etc 
{ _inToken = NO; } 

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if (_inToken) { 
     _token = string; 
     [parser abortParsing]; 
    } 
} 
0

您應該使用XML解析器。 這是很容易使用,全力以赴以下步驟獲得最好的結果:

從創建XMLParser的的NSXMLParser類的子類,讓您擁有一個NSXMLParser.h和NSXMLParser.m類

您的.h類必須像這樣的:

#import <Foundation/Foundation.h> 

@interface XMLParser : NSXMLParser <NSXMLParserDelegate>{ 

    NSUInteger parsedCounter; 
    BOOL accumulatingParsedCharacterData; 
    BOOL didAbortParsing; 
} 
@property (nonatomic, strong) NSMutableString *currentParsedCharacterData; 
@property (nonatomic, strong) NSMutableArray *currentParsedCharacterArray; 
@end 

而且.M類:

#import "XMLParser.h" 

@implementation XMLParser 

#pragma mark Parser constants 

// Limit the number of parsed data to 100. 
static const NSUInteger kMaximumNumberOfFilesToParse = 100; 

static NSUInteger const kSizeOfFileBatch = 10; 

// Reduce potential parsing errors by using string constants declared in a single place. 
static NSString * const kEntryElementName = @"dlResult"; 
static NSString * const kStringElementName = @"string"; 


#pragma mark NSXMLParser delegate methods 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { 

// NSLog(@"didStart"); 
    // If the number of parsed earthquakes is greater than kMaximumNumberOfEarthquakesToParse, abort the parse. 
    if (parsedCounter >= kMaximumNumberOfFilesToParse) { 
     // Use the flag didAbortParsing to distinguish between this deliberate stop and other parser errors. 
     didAbortParsing = YES; 
     [self abortParsing]; 
    } 
    if ([elementName isEqualToString:kEntryElementName]) { 
     _currentParsedCharacterArray = [[NSMutableArray alloc]init]; 

    } else if ([elementName isEqualToString:kStringElementName]) { 

     accumulatingParsedCharacterData = YES; 
     _currentParsedCharacterData = [[NSMutableString alloc]init]; 
    } 
} 

// return string between tags 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
// NSLog(@"foundCh"); 
    if (accumulatingParsedCharacterData) { 
     // If the current element is one whose content we care about, append 'string' 
     // to the property that holds the content of the current element. 
     [_currentParsedCharacterData appendString:string]; 
     NSLog(@"currentParsedCharacterData:%@",_currentParsedCharacterData); 
    } 
} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
// NSLog(@"didEnd"); 

    if ([elementName isEqualToString:kStringElementName]) { 
     [_currentParsedCharacterArray addObject:_currentParsedCharacterData]; 

    } 
    accumulatingParsedCharacterData = NO; 
} 

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { 
     if (didAbortParsing == NO) { 
     // Pass the error to the main thread for handling. 
     [self performSelectorOnMainThread:@selector(handleError:) withObject:parseError waitUntilDone:NO]; 
    } 
} 

@end 

在.M類有兩個常量字符串:

static NSString * const kEntryElementName = @"dlResult"; 
static NSString * const kStringElementName = @"string"; 

這些都是字符串變量,你應該實現標籤「狀態」,「原因」,「令牌」

從連接類,發送數據連接XMLParser的類象下面這樣:

@autoreleasepool { 

    // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable 
    // because it gives less control over the network, particularly in responding to connection errors. 
    // 
     XMLParser *parser = [[XMLParser alloc] initWithData:data]; 

     parser.currentParsedCharacterArray = [NSMutableArray array]; 
     parser.currentParsedCharacterData = [NSMutableString string]; 
     [parser setDelegate:parser]; 

     [parser parse]; 

     // depending on the total number of earthquakes parsed, the last batch might not have been a "full" batch, and thus 
     // not been part of the regular batch transfer. So, we check the count of the array and, if necessary, send it to the main thread. 

     if ([parser.currentParsedCharacterArray count] > 0) { 
      // send parsed data to another class or ... 
      // parser.currentParsedCharacterArray is parsed data 
     } 
     parser.currentParsedCharacterArray = nil; 
     parser.currentParsedCharacterData = nil; 
    } 

如果您有任何問題,請問我!

+0

嗨,謝謝你的建議。爲了讓你知道,我剛剛在3天前開始閱讀關於objective -c的內容。因此,如果我的問題聽起來很愚蠢,我很抱歉。我在哪裏指定「標記」?而且,我如何在主文件中實際執行它。我已閱讀NSXML文檔,但我仍然不太明白。 –

+0

哦,我不明白下面的兩行:「elementName isEqualToString:kEntryElementName」和「[elementName isEqualToString:kStringElementName]」。他們爲什麼要尋找「dlResult」和「string」? –

+0

這是可以的!我知道使用Objective-C編碼在第一個月並不容易! –

相關問題