How to get the name and value of attributes from xml when using libxml2 sax parser?

落爺英雄遲暮 提交于 2019-12-03 16:19:00

From looking at the linked documentation I'd think something like this might work:

    for (int i=0; i<nb_attributes; i++) 
    { 
        // if( *attributes[4] != '\0' ) // something needed here to null terminate the value
        NSString* key = [NSString stringWithCString: attributes[0] encoding: xmlencoding];
        NSString* val = [NSString stringWithCString: attributes[3] encoding: xmlencoding];
        [attributeDict setValue:val forKey:key];
        attributes += 5;
    } 

This assumes that there are always 5 string pointers for each attribute. As it is not otherwise noted I think it is safe to assume that the value string is null terminated and the end pointer is only given to allow easy length calculation. In case the end pointer does not point to a null char you would need to interpret only the chars from attributes[3] up to attributes[4] as value string (length = attributes[4]-attributes[3]).

xmlencoding probably needs to be the encoding of the xml document/entity except libxml2 does some conversion already although this seems unlikely as it typedefs xmlChar to unsigned char.

For Others, based on x4u answer and tksohishi comment:

 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)
 {

        NSLog(@"localname = %s",localname);

        if(nb_attributes>0)
        {
            NSMutableDictionary * attributeDict =[[NSMutableDictionary alloc] initWithCapacity: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]; // it'll be required // [val release];
                [attributeDict setValue:val forKey:key];
                attributes += 5;
            }
        }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!