我正在使用解析器从XML文件中获取数据.我使用libxml2来提取数据.我无法从节点获取属性.我只发现nb_attributes得到了属性的计数.
Mat*_*owe 10
我认为joostk意味着属性 - >孩子,给出这样的东西:
xmlAttr* attribute = node->properties;
while(attribute)
{
xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1);
//do something with value
xmlFree(value);
attribute = attribute->next;
}
Run Code Online (Sandbox Code Playgroud)
看看它是否适合你.
小智 5
我想我找到了为什么你只有 1 个属性(至少发生在我身上)。
问题是我读取了第一个节点的属性,但下一个是文本节点。不知道为什么,但是节点->属性给了我对内存的不可读部分的引用,所以它崩溃了。
我的解决方案是检查节点类型(元素为1)
我正在使用阅读器,所以:
xmlTextReaderNodeType(reader)==1
Run Code Online (Sandbox Code Playgroud)
您可以从http://www.xmlsoft.org/examples/reader1.c获取完整代码并添加此代码
xmlNodePtr node= xmlTextReaderCurrentNode(reader);
if (xmlTextReaderNodeType(reader)==1 && node && node->properties) {
xmlAttr* attribute = node->properties;
while(attribute && attribute->name && attribute->children)
{
xmlChar* value = xmlNodeListGetString(node->doc, attribute->children, 1);
printf ("Atributo %s: %s\n",attribute->name, value);
xmlFree(value);
attribute = attribute->next;
}
}
Run Code Online (Sandbox Code Playgroud)
到第 50 行。
尝试类似的方法:
xmlNodePtr node; // Some node
NSMutableArray *attributes = [NSMutableArray array];
for(xmlAttrPtr attribute = node->properties; attribute != NULL; attribute = attribute->next){
xmlChar *content = xmlNodeListGetString(node->doc, attribute->children, YES);
[attributes addObject:[NSString stringWithUTF8String:content]];
xmlFree(content);
}
Run Code Online (Sandbox Code Playgroud)