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

using namespace std;

#include <QtCore/QFile>
#include <QtXML/QXmlSimpleReader>

class MySaxParser : public QXmlDefaultHandler
{
    private:
        QString buf;
    public:
        virtual bool characters(const QString &ch);
        virtual bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts);
        virtual bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName);
};

// accumulate text (note: can be called multiple times for a text node)
bool MySaxParser::characters(const QString &ch)
{
    buf += ch;
    return true;
}

// process start element
bool MySaxParser::startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts)
{
    // if employee element find no and print
    if(localName == "employee")
    {
        int no = atts.value("no").toInt();
        cout << "no = " << no << endl;
    }
    // if sub elements name or role start accumulating
    if(localName ==  "name" || localName == "role")
    {
        buf = "";
    }
    return true;
}

// process end element
bool MySaxParser::endElement(const QString &namespaceURI, const QString &localName, const QString &qName)
{
    // if sub elements name or role stop accumulating and print
    if(localName == "name")
    {
        string name = buf.toStdString();
        cout << "name = " << name << endl;
    }
    if(localName == "role")
    {
        string role = buf.toStdString();
        cout << "role = " << role << endl;
    }
    return true;
}

const char *XML_FILE = "employees.xml";

void realmain()
{
    // process file with MySaxParser as event handler
    QXmlSimpleReader parser;
    parser.setContentHandler(new MySaxParser());
    parser.parse(new QXmlInputSource(new QFile(XML_FILE)));
}
