libxml2恐怕是linux下最著名的xml解析库了,其sax API不仅解析效率高,速度快,而且内存占用率更是出奇的低。因此是iphone开发中必不可少的xml解析库。
但sax解析是基于事件驱动的,使用门槛较dom解析为高,不容易为初学者掌握,代码难于阅读和理解。比如笔者写过这样的代码:
//解析元素体时触发
- (void)charactersFound:(const xmlChar*)ch
len:(int)len
{
NSString* string;
string = [[NSString alloc] initWithBytes:ch length:len encoding:NSUTF8StringEncoding];
// 取login_status元素体
switch (flag) {
case 1:
[item setObject:string forKey:@"GNID"];
break;
case 2:
[item setObject:string forKey:@"YWBH"];
break;
case 3:
[item setObject:string forKey:@"QDRQ"];
break;
}
}
- (void)charactersFound:(const xmlChar*)ch
len:(int)len
{
[string appendString:[[NSString alloc] initWithBytes:ch length:len encoding:NSUTF8StringEncoding]];
//解析元素结束标记时触发
- (void)endElementLocalName:(const xmlChar*)localname
prefix:(const xmlChar*)prefix URI:(const xmlChar*)URI
{
switch (flag) {
case 1:
[item setObject:string forKey:@"GNID"];
break;
case 2:
[item setObject:string forKey:@"YWBH"];
break;
case 3:
[item setObject:string forKey:@"QDRQ"];
break;
}
flag=0;
}
然后在元素开始标记回调方法startElementLocalName中,重置string变量:
[string release];
string=[[NSMutableString alloc]init];