/* 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 <libxml/parser.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 xmlChar *ch,   int len)
{
    memcpy(state->buf + state->len, ch, len);
    state->len += len;
}

/* process start element */
void onStartElement(struct state *state, const xmlChar *name, const xmlChar **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 xmlChar *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()
{
    xmlSAXHandler *myhandler;
    struct state mystate;
    // process file with specified event handlers
    myhandler = malloc(sizeof(xmlSAXHandler));
    memset(myhandler, 0, sizeof(xmlSAXHandler));
    myhandler->characters = (charactersSAXFunc)onCharacters;
    myhandler->startElement = (startElementSAXFunc)onStartElement;
    myhandler->endElement = (endElementSAXFunc)onEndElement;
    mystate.len = 0;
    mystate.buf = malloc(10000);
    xmlSAXUserParseFile(myhandler, &mystate, XML_FILE);
    /* */
    return EXIT_SUCCESS;
}
