我意識到你在幾天前問過這個問題,但我想我會給你一個如何使用NSXMLParser的例子。我不記得我從哪裏學到這些,但這是我在項目中使用的技術。
您可以創建自己的類,像這樣創建自己的類並在網絡調用結束後實例化它並調用「parseData:」函數,或者將所有這些mumbo jumbo粘貼到處理網絡代碼的類中並調用函數從那裏。
#import "ThaweExampleParser.h"
@interface ThaweExampleParser() <NSXMLParserDelegate>
@property (nonatomic) BOOL accumulatingParsedCharacterData;
@property (nonatomic, strong) NSMutableString *currentParsedCharacterData;
@property (nonatomic, strong) NSMutableDictionary *parsedContents;
@end
@implementation ThaweExampleParser
@synthesize accumulatingParsedCharacterData;
@synthesize currentParsedCharacterData;
@synthesize parsedContents;
/*
* This function you would call when your network connection finishes.
* You pass in the NSMutableData you collected during the request.
*/
- (void)parseData:(NSData *)webData
{
self.currentParsedCharacterData = [NSMutableString string];
self.parsedContents = [NSMutableDictionary dictionary];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:webData];
parser.delegate = self;
[parser parse];
}
/*
* The parsed calls this function everytime it finds a new tag.
* A tag looks like "<mediaurl>"
* So in this case we want to turn or BOOL to YES so that the last function collects only the characters we care about.
*/
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"mediaurl"])
{
self.accumulatingParsedCharacterData = YES;
[self.currentParsedCharacterData setString:@""];
}
}
/*
* Much the previous function except the tag looks like "</mediaurl>"
* Turn our BOOL to NO because we are done collecting characters for the moment.
* We also are saving the important data to a dictionary so that you can use it later.
*/
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"mediaurl"])
{
self.accumulatingParsedCharacterData = NO;
[self.parsedContents setObject:[self.currentParsedCharacterData copy] forKey:elementName];
}
}
/*
* The parser calls this function everytime it finds characters.
* In your case it would call it maybe 5 or 6 times with data that you dont want to collect.
* So we use a BOOL to control what we collect;
*/
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (self.accumulatingParsedCharacterData) [self.currentParsedCharacterData appendString:string];
}
@end