Davide C
Davide C

Reputation: 976

C extract data from XML

I have a simple xml file like this stored in a char[].

<?xml-stylesheet type='text/xsl' href='http://prova'?>
<ns2:operation-result xmlns:ns1="http://www.w3.org/1999/xlink" xmlns:ns2="http://www.prova.it/pr/a" operation-start="2015-01-12T15:22:46.890+01:00" operation-end="2015-01-12T15:22:46.891+01:00"><ns2:error code="ROSS-A001"><ns2:msg>Error</ns2:msg></ns2:error></ns2:operation-result>

I need a simple C routine to extract only the error code (in this case ROSS-A001) and the error message between and put it in two char[].

How can i do it?

Thank you very much

Upvotes: 0

Views: 859

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

What about

char *extractErrorCode(const char *xml)
{
    char  *pointer;
    char  *result;
    char  *tail;
    size_t length;

    /* advance the pointer to the = character, and skip the " -> +1 */
    pointer = strstr(xml, "error code=") + strlen("error code=") + 1;
    result  = NULL;
    if (pointer == NULL)
        return NULL;

    length = 0;
    tail   = strchr(pointer, '>');
    if (tail == NULL)
        return NULL;
    /* -1 skip the trailing " */
    length = tail - pointer - 1;
    if (length > 0)
    {
        result = malloc(1 + length);
        if (result == NULL)
            return NULL;
        result[length] = '\0';

        memcpy(result, pointer, length);
    }

    return result;
}

remember to free the return value if it's not NULL

Upvotes: 1

Related Questions