2012-05-29 55 views
7

这是我想要使用libxml解析进行解析的xml结构。如何使用libxml解析解析xml数据

enter image description here

enter image description here

我怎样才能为 “运动” 标签的属性值即ID和即网址大小 “图像” 标签。

如果我使用这些值,我可以提取“代码”标记和“名称”标记的值。

static const char *kName_campaign = "campaign"; 
static const NSUInteger kLength_campaign = 9; 
static const char *kName_code = "code"; 
static const NSUInteger kLength_code = 5; 
static const char *kName_name = "name"; 
static const NSUInteger kLength_name = 5; 

然后我得到当前和即将到来的活动的代码和名称在一起。 这是我在代理中使用的代码,它在解析完成时被调用。

static void endElementSAX(void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) 
{  
    LibXMLParser *parser = (LibXMLParser *)ctx; 

    if (parser.parsingASong == NO) return; 

    if (prefix == NULL) 
    { 
     if (!strncmp((const char *)localname, kName_campaign, kLength_campaign)) 
     { 
      [parser finishedCurrentSong]; 
      parser.parsingASong = NO; 
     } 
     else if (!strncmp((const char *)localname, kName_code, kLength_code)) 
     { 
      parser.currentSong.title = [parser currentString]; 
      NSLog(@"Code :: %@",[parser currentString]); 
     } 
     else if (!strncmp((const char *)localname, kName_name, kLength_name)) 
     { 
      parser.currentSong.category = [parser currentString]; 
      NSLog(@"Name :: %@",[parser currentString]); 
     } 
    } 
} 

我怎样才能获得的属性值,从开始到从“运动”标签ID的底部。 url and size from“image”tag?

+0

真的感谢名单为垫。 – NiKKi

+0

出于兴趣,你为什么不使用'NSXMLParser'? –

+0

因为它更快速和内存友好... – NiKKi

回答

6
static void startElementSAX(void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, 
int nb_defaulted, const xmlChar **attributes) 
{ 

if (nb_attributes > 0) 
{ 
    NSMutableDictionary* attributeDict = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)[NSNumber numberWithInt:nb_attributes]]; 
    for (int i=0; i<nb_attributes; i++) 
    { 
     NSString* key = [NSString stringWithCString:(const char*)attributes[0] encoding:NSUTF8StringEncoding]; 
     NSString* val = [[NSString alloc] initWithBytes:(const void*)attributes[3] length:(attributes[4] - attributes[3]) encoding:NSUTF8StringEncoding]; 
     attributes += 5; 

     [attributeDict setValue:val forKey:key]; 
    } 
} 
} 

试试这个..