/* 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>

#define XML_FILE "employees.xml"

int main()
{
    xmlDoc *doc;
    xmlNode *root;
    xmlNode *employee;
    xmlNode *element;
    xmlChar *no;
    xmlChar *name;
    xmlChar *role;
    /* 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;
    }
    /* iterate over all elements below root (employee elements) */
    root = xmlDocGetRootElement(doc);
    employee = root->children;
    do
    {
        if(!xmlIsBlankNode(employee))
        {
            /* find attribute no */
            no = xmlGetProp(employee, "no");
            /* find sub elements name and role */
            element = employee->children;
            do
            {
                if(!xmlIsBlankNode(element))
                {
                    if(strcmp(element->name, "name") == 0)
                    {
                        name = element->children->content;
                    }
                    if(strcmp(element->name, "role") == 0)
                    {
                        role = element->children->content;
                    }
                }
                element = element->next;
            }
            while(element != NULL);
            /* print */
            printf("no=%s\n", no);
            printf("name=%s\n", name);
            printf("role=%s\n", role);
        }
        employee = employee->next;
    }
    while(employee != NULL);
    /* add employee */
    employee = xmlNewNode(NULL, "employee");
    xmlNewProp(employee, "no", "4");
    element = xmlNewNode(NULL, "name");
    xmlAddChild(element, xmlNewText("Dave D"));
    xmlAddChild(employee, element);
    element = xmlNewNode(NULL, "role");
    xmlAddChild(element, xmlNewText("Intern"));
    xmlAddChild(employee, element);
    xmlAddChild(root, employee);
    /* write out */
    xmlDocDump(stdout, doc);
    /* clean up */
    xmlFreeDoc(doc);
    xmlCleanupParser();
    /* */
    return EXIT_SUCCESS;
}
