What is the right way to get attribute value in li

2019-05-11 19:58发布

问题:

I am using the SAX interface of libXML to write a XML parser application in C++.

<abc value="xyz &quot;pqr&quot;"/>

how do I parse this attribute?

I tried using

void startElementNsSAX2Func(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)

, incrementing attributes parameter( and checking for a " to indicate the end of the attribute value).

It works for all the attributes other than *&quot;* appearing in the attribute value.

What is the right method to parse these kind of attribute values?

Thanks

回答1:

try this function:

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

YOu can use it like this:

char *value = getAttributeValue("value", nb_attributes, attributes);
printf("%s\n", value);
free(value);