如何从libxml2中的节点获取属性

时间:2009-07-07 13:03:42

标签: c libxml2

我正在使用解析器从XML文件中获取数据。我使用libxml2来提取数据。我无法从节点获取属性。我只找到nb_attributes来获取属性的计数。

6 个答案:

答案 0 :(得分: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;
}

看看它是否适合你。

答案 1 :(得分:7)

如果您只想要一个属性,请使用xmlGetPropxmlGetNsProp

答案 2 :(得分:3)

我想我找到了为什么你只有1个属性(至少它发生在我身上)。

问题是我读取了第一个节点的属性,但接下来是一个文本节点。不知道为什么,但是node->属性给了我一个不可读的内存部分的引用,所以它崩溃了。

我的解决方案是检查节点类型(元素是1)

我正在使用读者,所以:

xmlTextReaderNodeType(reader)==1

您可以从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;
    }
}

到第50行。

答案 3 :(得分:1)

尝试类似:

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

答案 4 :(得分:0)

如果你使用SAX方法startElementNs(...),你正在寻找这个函数:

xmlChar *getAttributeValue(char *name, const xmlChar ** attributes,
           int nb_attributes)
{
int i;
const int fields = 5;    /* (localname/prefix/URI/value/end) */
xmlChar *value;
size_t size;
for (i = 0; i < nb_attributes; i++) {
    const xmlChar *localname = attributes[i * fields + 0];
    const xmlChar *prefix = attributes[i * fields + 1];
    const xmlChar *URI = attributes[i * fields + 2];
    const xmlChar *value_start = attributes[i * fields + 3];
    const xmlChar *value_end = attributes[i * fields + 4];
    if (strcmp((char *)localname, name))
        continue;
    size = value_end - value_start;
    value = (xmlChar *) malloc(sizeof(xmlChar) * size + 1);
    memcpy(value, value_start, size);
    value[size] = '\0';
    return value;
}
return NULL;
}

用法:

char * value = getAttributeValue("atrName", attributes, nb_attributes);
// do your magic
free(value);

答案 5 :(得分:0)

我发现使用libxml2(通过C ++中的libxml ++)最简单的方法是使用eval_to_XXX方法。他们评估XPath表达式,因此您需要使用@property语法。

例如:

std::string get_property(xmlpp::Node *const &node) {
    return node->eval_to_string("@property")
}