我一直试图通过使用 libxml2 解析 iPhone 应用程序上的 api 来检测一些通用 xml 中属性的名称和值对。对于我的项目来说,解析速度非常重要,所以我决定使用 libxml2 本身而不是使用 NSXMLParser。
现在,参考 XMLPerformance(它是 iPhone SDK 的示例,用于 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];
}
}
}
I saw libxml2 文档 http://xmlsoft.org/html/libxml-parser.html#startElementNsSAX2Func,但我不能。如果您是出色的黑客,请帮助我:)
通过查看链接的文档,我认为这样的方法可能有效:
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 个字符串指针。由于没有另外说明,我认为可以安全地假设值字符串以 null 结尾,并且仅给出结束指针以允许轻松计算长度。如果结束指针不指向空字符,则只需将从属性 [3] 到属性 [4] 的字符解释为值字符串(长度 = 属性 [4]-属性 [3])。
xmlencoding 可能需要是 xml 文档/实体的编码,除了 libxml2 已经做了一些转换,尽管这似乎不太可能,因为它将 xmlChar 类型定义为无符号字符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)