What is the right way to get attribute value in libXML sax parser (C++)?

巧了我就是萌 提交于 2019-12-10 10:02:46

问题


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


来源:https://stackoverflow.com/questions/24785178/what-is-the-right-way-to-get-attribute-value-in-libxml-sax-parser-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!