0

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

3
  • In which case? Are you missing something? Are you asking for a XML parser written in C? Commented Jan 12, 2015 at 14:39
  • possible duplicate of XML Parser for C Commented Jan 12, 2015 at 15:01
  • Even though it feels like massive overkill for such a relatively simple task, use a real XML parsing library (such as libxml2). I've hand-hacked my own XML parser in the past, and it wasn't worth the effort. Commented Jan 12, 2015 at 15:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.