XML 是一種自描述的資料交換格式,多年來在各式程式語言間扮演重要角色。它長得像 HTML,但更嚴謹:每個標籤都必須成對,以 <> 開始、</> 結束。iOS 內建的 NSXMLParser 屬於 SAX 式的串流解析,記憶體佔用低,適合處理大型文件。
<users>
<user id="001">
<name>張三</name>
<password>123456</password>
<nickname>小張</nickname>
<description>1111111111</description>
</user>
<user id="002">
<name>李四</name>
<password>2222222</password>
<nickname>小四兒</nickname>
<description>李四是個好學生</description>
</user>
<user id="003">
<name>王五</name>
<password>88888888</password>
<nickname>小五</nickname>
<description>1234567890</description>
</user>
</users>
假設資料已讀取並存在 data 中。
建立一個繼承自 NSObject 的類,命名為 userInfo,用來承載單筆資料:
@property (nonatomic, copy) NSString *uID; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *password; @property (nonatomic, copy) NSString *nickname; @property (nonatomic, copy) NSString *description;
再建立 userParser,同樣繼承自 NSObject,負責整個解析流程。
userParser.h:
#import <Foundation/Foundation.h> #import "user.h" @interface userParser : NSObject <NSXMLParserDelegate> @property (nonatomic, retain) NSMutableArray *array; // 存放解析結果 @property (nonatomic, retain) user *people; // 目前處理中的一筆資料 @property (nonatomic, copy) NSMutableString *buffer; // 暫存標籤內的文字 - (void)parserWithString:(NSString *)string; @end
userParser.m:
#import "userParser.h"
@implementation userParser
- (void)parserWithString:(NSString *)string {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
parser.delegate = self;
[parser parse];
}
#pragma mark --- NSXMLParserDelegate ---
// 文件開始
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"it begin");
}
// 文件結束,此時可統一輸出結果
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"it is over");
for (int i = 0; i < _array.count; i++) {
user *user = _array[i];
NSLog(@"%@,%@,%@,%@,%@", user.uID, user.name, user.password, user.nickname, user.description);
}
}
// 遇到開始標籤,attributeDict 內是該標籤的屬性
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"users"]) {
_array = [[NSMutableArray alloc] init];
} else if ([elementName isEqualToString:@"user"]) {
_people = [[user alloc] init];
_people.uID = [attributeDict objectForKey:@"id"]; // 取出 <user id="3"> 的屬性
} else if ([elementName isEqualToString:@"name"]) {
_buffer = [[NSMutableString alloc] init];
} else if ([elementName isEqualToString:@"password"]) {
_buffer = [[NSMutableString alloc] init];
} else if ([elementName isEqualToString:@"nickname"]) {
_buffer = [[NSMutableString alloc] init];
} else if ([elementName isEqualToString:@"description"]) {
_buffer = [[NSMutableString alloc] init];
}
}
// 遇到結束標籤,把暫存的文字交給對應的模型屬性
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"name"]) {
_people.name = _buffer;
} else if ([elementName isEqualToString:@"password"]) {
_people.password = _buffer;
} else if ([elementName isEqualToString:@"nickname"]) {
_people.nickname = _buffer;
} else if ([elementName isEqualToString:@"description"]) {
_people.description = _buffer;
} else if ([elementName isEqualToString:@"user"]) {
[_array addObject:_people];
}
}
// 讀取標籤之間的文字內容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
// 去掉頭尾的空白與換行,避免文字被污染
[_buffer appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
@end
在 view controller 中建立 userParser 實例,呼叫 parserWithString: 即可:
userParser *uparser = [[userParser alloc] init]; [uparser parserWithString:user];
把資料解析與畫面顯示分開寫,有助於降低耦合,也符合 MVC 的分層精神——這正是上面把邏輯獨立到 userParser 的原因。
另一點是 foundCharacters: 可能被多次呼叫。系統不會保證一次就把整段文字交給你,尤其內容較長或含實體參照時更明顯。示範中之所以用 NSMutableString 持續 append 而非直接指派,就是為了應付這個特性;若改成「每次 foundCharacters: 就覆寫 _buffer」,遇到長文字時只會留下最後一塊碎片。