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

using namespace std;

#include <xercesc/parsers/SAXParser.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>

using namespace xercesc;

const char *XML_FILE = "employees.xml";

// hackish utility functions - do not use in production
static XMLCh buf[10][1000];
static int bufix = -1;

static XMLCh *UTF16(const char *s)
{
    bufix = (bufix + 1) % 10;
    XMLString::transcode(s, buf[bufix], sizeof(buf[bufix]) - 1);
    return buf[bufix];
}

static char *UTF8(const XMLCh *s)
{
    return XMLString::transcode(s);
}

class MySaxParser : public HandlerBase
{
    private:
        XMLCh buf[10000]; // hardcoded size - do not use in production
        int buflen;
    public:
        void characters (const XMLCh *const chars, const XMLSize_t length);
        void startElement(const XMLCh *const name, AttributeList& attributes);
        void endElement(const XMLCh *const name);
};

// accumulate text (note: can be called multiple times for a text node)
void MySaxParser::characters(const XMLCh *const chars, const XMLSize_t length)
{
    memcpy(buf + buflen, chars, length * sizeof(XMLCh));
    buflen += length * sizeof(XMLCh);
}

// process start element
void MySaxParser::startElement(const XMLCh *const name, AttributeList& atts)
{
    // if employee element find no and print
    if(strcmp(UTF8(name), "employee") == 0)
    {
        int no = atoi(UTF8(atts.getValue(UTF16("no"))));
        cout << "no = " << no << endl;
        
    }
    // if sub elements name or role start accumulating
    if(strcmp(UTF8(name), "name") == 0 || strcmp(UTF8(name), "role") == 0)
    {
        buflen = 0;
    }
}

// process end element
void MySaxParser::endElement(const XMLCh *const name)
{
    // if sub elements name or role stop accumulating and print
    if(strcmp(UTF8(name), "name") == 0)
    {
        memset(buf + buflen, 0, sizeof(XMLCh));
        char *name = UTF8(buf);
        cout << "name = " << name << endl;
    }
    if(strcmp(UTF8(name), "role") == 0)
    {
        memset(buf + buflen, 0, sizeof(XMLCh));
        char *role = UTF8(buf);
        cout << "role = " << role << endl;
    }
}

int main()
{
    try
    {
        XMLPlatformUtils::Initialize();
        // process file with MySaxParser as event handler
        SAXParser *parser = new SAXParser();
        parser->setDocumentHandler(new MySaxParser());
        parser->parse(XML_FILE);
        //
        XMLPlatformUtils::Terminate();
    }
    catch (const XMLException &ex)
    {
        cout << UTF8(ex.getMessage()) << endl;
        exit(1);
    }
    catch (const SAXParseException &ex)
    {
        cout << UTF8(ex.getMessage()) << endl;
        exit(1);
    }
    catch (...)
    {
        cout << "Ooops" << endl;
        exit(1);
    }
    return 0;
}
