使用libxml2 sax解析器时如何从xml获取属性的名称和值?

tks*_*shi 4 c xml iphone objective-c libxml2

我试图通过使用libxml2来解析iPhone应用程序上的api,试图在一些通用xmls中检测属性的名称和值.对于我的项目,解析速度非常重要,因此我决定使用libxml2本身而不是使用NSXMLParser.

现在,作为XMLPerformance的参考,它是用于NSXMLParser和libxml2之间的解析基准的iPhone SDK的示例,我试图在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];
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

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

x4u*_*x4u 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;
    } 
Run Code Online (Sandbox Code Playgroud)

这假设每个属性总是有5个字符串指针.由于没有另行说明,我认为可以安全地假设值字符串为空终止,并且仅给出结束指针以允许容易的长度计算.如果结束指针未指向空字符,则需要仅将属性[3]中的字符解释为属性[4]作为值字符串(length = attributes [4] -attributes [3]).

xmlencoding可能需要是xml文档/实体的编码,除了libxml2已经进行了一些转换,尽管这看起来不太可能,因为它将typedefs xmlChar转换为unsigned char.

  • 谢谢,x4u!最后,它就是这样的.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]; //它将被要求// [val release]; (3认同)