Read Xml Qt

Posted by k0il inside On Saturday, November 5, 2011 0 komentar

Membuat Aplikasi Desktop Yang bisa membaca Xml.... sepertinya keren tuh heheheh,..
berikut ini saya akan share code bagai mana membuat aplikasi desktop menggunakan QT CREATOR yang bisa untuk mebuka dan membaca file XML, utnuk format dari xmlnya sendiri adalah sebagai berikut :

<?xml version="1.0" encoding="UTF-8" ?>
<persons>
 <person firstname="kamlesh" surname="sangani" number="1234" />
 <person firstname="jaydeep" surname="sapariya" number="51234" />
 <person firstname="rishit" surname="barochia" number="61234" />
 <person firstname="pritesh" surname="raithatha" number="81234" />
 <person firstname="jignesh" surname="luhar" number="61234" />
</persons>
Dan untuk filenya adalah sebagai berikut :

main.cpp
#include "qxsrexample.h"

#include <QtGui>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QXSRExample w;
    w.showMaximized();
    return a.exec();
}

qxsrexample.h

#ifndef QXSREXAMPLE_H
#define QXSREXAMPLE_H

#include <QtGui/QMainWindow>
#include <QtGui/QScrollArea>
#include <QtGui/QFrame>
#include <QtGui/QVBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QGroupBox>
#include <QtGui/QFormLayout>
#include <QtGui/QMessageBox>

#include <QtCore/QPointer>
#include <QtCore/QFile>
#include <QtCore/QIODevice>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QString>

#include <QtXml/QXmlStreamReader>

class ContactDatabse
{
public:
 ContactDatabse(QString firstName, QString surName, QString phoneNumber);
 ~ContactDatabse();
 QString getFirstName();
 QString getSurName();
 QString getPhoneNumber();
private:
 QString firstName;
 QString surName;
 QString phoneNumber;
};

class QXSRExample : public QMainWindow {
 Q_OBJECT

public:
 QXSRExample(QWidget *parent = 0);
 ~QXSRExample();

private slots:
 void parseXML();

private:
 QPointer<QVBoxLayout> _layout;

 void setupUI();
 void addPersonsToUI();
 void parsePerson(QXmlStreamReader& reader);
 QList<ContactDatabse> database;
};


#endif // QXSREXAMPLE_H

qxsrexample.cpp
#include "qxsrexample.h"
#include <QMessageBox>
#include <QDebug>

ContactDatabse::ContactDatabse(QString fName, QString sName, QString pNumber)
{
 firstName = fName;
 surName =sName;
 phoneNumber = pNumber;
}

QString ContactDatabse::getFirstName()
{
 return firstName;
}

QString ContactDatabse::getSurName()
{
 return surName;
}

QString ContactDatabse::getPhoneNumber()
{
 return phoneNumber;
}

ContactDatabse::~ContactDatabse()
{
}

QXSRExample::QXSRExample(QWidget *parent) : QMainWindow(parent) {
 setupUI();
}

QXSRExample::~QXSRExample() {

}

void QXSRExample::setupUI() {
 /* UI container */
 QFrame* frame = new QFrame(this);
 /* Layout we'll put our widgets. */
 _layout = new QVBoxLayout;
 frame->setLayout(_layout);
 _layout->addWidget(new QLabel("<h1>QXSR Example</h1>"), 0, Qt::AlignCenter);

 QPushButton* parseXML = new QPushButton("Parse XML from example.xml");
 _layout->addWidget(parseXML);
 /* We'll parse the XML when the button is clicked. */
 connect(parseXML, SIGNAL(clicked()),
         this, SLOT(parseXML()));

 /* Let's make the UI scale so that we can scroll it. */
 QScrollArea* scrollArea = new QScrollArea;
 scrollArea->setWidget(frame);
 scrollArea->setWidgetResizable(true);

 setCentralWidget(scrollArea);
}

void QXSRExample::parseXML() 

 {
  /* We'll parse the example.xml */
  QFile* file = new QFile(":/example.xml");
  /* If we can't open it, let's show an error message. */
  if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
   QMessageBox::critical(this, 
                         "QXSRExample::parseXML", 
                         "Couldn't open example.xml", 
                         QMessageBox::Ok);
   return;
  }
  /* QXmlStreamReader takes any QIODevice. */
  QXmlStreamReader xml(file);
  QList< QMap<QString,QString> > persons;
  /* We'll parse the XML until we reach end of it.*/
  while(!xml.atEnd() &&
        !xml.hasError()) {
   /* Read next element.*/
   QXmlStreamReader::TokenType token = xml.readNext();
   /* If token is just StartDocument, we'll go to next.*/
   if(token == QXmlStreamReader::StartDocument) {
    continue;
   }
   /* If token is StartElement, we'll see if we can read it.*/
   if(token == QXmlStreamReader::StartElement) {
    /* If it's named persons, we'll go to the next.*/
    if(xml.name() == "persons") {
     continue;
    }
    /* If it's named person, we'll dig the information from there.*/
    if(xml.name() == "person") 
    {
     this->parsePerson(xml);
    }
   }
  }
  /* Error handling. */
  if(xml.hasError()) {
   QMessageBox::critical(this, 
                         "QXSRExample::parseXML", 
                         xml.errorString(), 
                         QMessageBox::Ok);
  }
  xml.clear();
 }

void QXSRExample::addPersonsToUI() 
{
 while(!database.isEmpty()) 
 {
  QGroupBox* personGB = new QGroupBox("Person");
  QFormLayout* layout = new QFormLayout;
  ContactDatabse person = database.takeFirst();
  layout->addRow("First name", new QLineEdit(person.getFirstName()));
  layout->addRow("Surname", new QLineEdit(person.getSurName()));
  layout->addRow("Phone Number", new QLineEdit(person.getPhoneNumber()));
  
  personGB->setLayout(layout);
  this->_layout->addWidget(personGB);
 }
}

void QXSRExample::parsePerson(QXmlStreamReader& xml)
{
 while (!xml.atEnd()) 
 {
 
  if (xml.isStartElement() && xml.name() == "person") 
  {
   QXmlStreamAttributes attrs = xml.attributes();
   
   QStringRef fName = attrs.value("firstname");
   QStringRef sName = attrs.value("surname");
   QStringRef pNumber = attrs.value("number");

     if (fName.isEmpty())
      {
      xml.readNext();
      continue;
      }
                          qDebug()<<fName.toString();
     
                        //ContactDatabse data(fName.toString(),sName.toString(),pNumber.toString());
                        //database.append(data);
  }
  else if(xml.isEndElement() && xml.name() == "persons") 
  {
   addPersonsToUI();
   return;
  }
  xml.readNext();
 }
}


0 komentar:

Post a Comment