How to get attributes from a node in libxml2

前端 未结 6 2062
孤街浪徒
孤街浪徒 2020-12-20 18:32

I am working on a parser to get data from an XML file. I am using libxml2 to extract data. I am a not able to get the attributes from nodes. I only found nb_attributes

6条回答
  •  失恋的感觉
    2020-12-20 19:26

    If you use SAX method startElementNs(...), this function is what you are looking for:

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

    Usage:

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

提交回复
热议问题