/* 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>
#include <libxml/tree.h>
#include <libxml/xpath.h>

#define XML_FILE "employees.xml"

int main()
{
    xmlDoc *doc;
    xmlXPathContext *ctx;
    xmlXPathObject *res;
    xmlXPathObject *res2;
    xmlNodeSet *employees;
    xmlNode *employee;
    xmlChar *no;
    xmlChar *name;
    xmlChar *role;
    int i;
    /* read from file to DOM tree */
    doc = xmlReadFile(XML_FILE, NULL, 0);
    if (doc == NULL)
    {
        fprintf(stderr, "Failed to parse %s\n", XML_FILE);
        return EXIT_FAILURE;
    }
    /* setup XPath */
    ctx = xmlXPathNewContext(doc);
    /* iterate over all employee elements */
    res = xmlXPathEval("//employee[@no>1 and role!='Intern']", ctx);
    employees = res->nodesetval;
    if(!xmlXPathNodeSetIsEmpty(employees))
    {
        for(i = 0; i < xmlXPathNodeSetGetLength(employees); i++)
        {
            employee = xmlXPathNodeSetItem(employees, i);
            // find attribute no
            res2 = xmlXPathNodeEval(employee, "@no", ctx);
            no = xmlXPathCastNodeSetToString(res2->nodesetval);
            // find sub elements name and role 
            res2 = xmlXPathNodeEval(employee, "name/text()", ctx);
            name = xmlXPathCastNodeSetToString(res2->nodesetval);
            res2 = xmlXPathNodeEval(employee, "role/text()", ctx);
            role = xmlXPathCastNodeSetToString(res2->nodesetval);
            /* print */
            printf("no=%s\n", no);
            printf("name=%s\n", name);
            printf("role=%s\n", role);
       }
    }
    /* clean up */
    xmlXPathFreeObject(res);
    xmlXPathFreeContext(ctx);
    xmlFreeDoc(doc);
    xmlCleanupParser();
    /* */
    return EXIT_SUCCESS;
}
