5

我被困在尝试通过使用 libxml2 解析 iPhone 应用程序上的 api 来检测某些通用 xmls 中属性的名称和值对。对于我的项目,解析速度真的很重要,所以我决定使用 libxml2 本身而不是使用 NSXMLParser。

现在,作为 iPhone SDK 的示例 XMLPerformance,用于 NSXMLParser 和 libxml2 之间的解析基准测试,我试图在下面的 XML 解析器处理程序之一中获取属性的详细信息,但我不知道如何检测它.

/* for example, <element key="value" /> */
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 = @""; /* expected: key */
            NSString* val = @""; /* expected: value */
            [attributeDict setValue:val forKey:key];
        }
     }
}

我看到了 libxml2 文档,但我看不到。如果你是伟大的黑客,请帮助我:)

4

2 回答 2

6

通过查看链接的文档,我认为这样的事情可能会起作用:

    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;
    } 

这假定每个属性总是有 5 个字符串指针。由于没有另外说明,我认为可以安全地假设值字符串为空终止,并且仅给出结束指针以允许轻松计算长度。如果结束指针不指向空字符,您只需将属性 [3] 到属性 [4] 的字符解释为值字符串(长度 = 属性 [4]-属性 [3])。

xmlencoding 可能需要是 xml 文档/实体的编码,除了 libxml2 已经进行了一些转换,尽管这似乎不太可能,因为它将 xmlChar 类型定义为 unsigned char。

于 2010-01-16T04:44:22.360 回答
0

对于其他人,基于 x4u 答案和 tksohishi 评论:

 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;
            }
        }
 }
于 2018-11-11T16:33:36.173 回答