iOS NSXMLParser

XML parser在iOS裡面有不少選擇,甚至不少第三方的parser都比官方強勁,不過這篇重點是介紹官方的NSXMLParser。

step1. 先在.h檔加入NSXMLParserDelegate
#import

@interface DemoXML : UIViewController {
//xml
NSXMLParser *parser;
NSString *parserCurrent;
}

//xml
@property (nonatomic,retain) NSString *parserCurrent;

@end


step2. .m檔的部份加入property部份
//xml
@synthesize parserCurrent;


step3. .m檔內需要進行parser的部份加入
//需要parser的URL
NSString *parserString = @"需要parser的URL";

//若有特別需要轉碼
NSString *escaped = [parserString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//NSXMLParser init
parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:escaped]];

//設定Delegate
[parser setDelegate:self];

//開始parser
[parser parse];


step4.設定Delegate的部份
//parser < XXXX>
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(@"elementName = %@", elementName);
//NSLog(@"elementName = %d", elementName.length);
//elementName就是其中XXX的部份
parserCurrent = elementName;
}

//parser
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(@"didEndElement => elementName = %@ || namespaceURI = %@ || qName = %@", elementName, namespaceURI, qName);

}

//parser <>XXXXXX
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"foundCharacters = %@",string);

//如果XML的Tag名稱與所需相同,就做以下動作
if([parserCurrent isEqual:@"title"]){
//Todo something
}
}

//parser結束
-(void) parserDidEndDocument:(NSXMLParser *)parser{
//todo something
}


相關連結
iOS Developer Library
iOS Developer Library - NSXMLParser
iOS Developer Library - NSXMLParserDelegate Protocol Reference

沒有留言:

張貼留言