/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <expat.h>

#define XML_FILE "employees.xml"

struct state
{
    int len;
    char *buf;
};

/* accumulate text (note: can be called multiple times for a text node) */
void onCharacters(struct state *state, const XML_Char *ch, int len)
{
    memcpy(state->buf + state->len, ch, len);
    state->len += len;
}

/* process start element */
void onStartElement(struct state *state, const XML_Char *name, const XML_Char **attrs)
{
    /* if employee element find no and print */
    if(strcmp(name, "employee") == 0)
    {
        printf("no=%s\n", attrs[1]); // [0] is first attribute name, [1] is first attribute value
    }
    /* if sub elements name or role start accumulating */
    if(strcmp(name, "name") == 0 || strcmp(name, "role") == 0)
    {
        state->len = 0;
    }
}

/* process end element */
void onEndElement(struct state *state, const XML_Char *name)
{
    /* if sub elements name or role stop accumulating and print */
    if(strcmp(name, "name") == 0)
    {
        state->buf[state->len] = 0;
        printf("name=%s\n", state->buf);
    }
    if(strcmp(name, "role") == 0)
    {
        state->buf[state->len] = 0;
        printf("role=%s\n", state->buf);
    }
}

int main()
{
    XML_Parser parser;
    struct state mystate;
    FILE *fp;
    char buf[100000];
    int buflen;
    int done;
    /* process file with specified event handlers */
    parser = XML_ParserCreate(NULL);
    XML_SetUserData(parser, &mystate);
    XML_SetElementHandler(parser, (XML_StartElementHandler)onStartElement, (XML_EndElementHandler)onEndElement);
    XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)onCharacters);
    mystate.len = 0;
    mystate.buf = malloc(10000);
    fp = fopen(XML_FILE, "r");
    do
    {
        buflen = fread(buf, 1, sizeof(buf), fp);
        done = buflen < sizeof(buf);
        XML_Parse(parser, buf, buflen, done);
    }
    while(!done);
    fclose(fp);
    XML_ParserFree(parser);
    /* */
    return 0;
}
