Qt/C++ - Lesson 011. XML files in Qt – Reading and Writing

Qt, QXmlStreamReader, QXmlStreamWriter, XML, xml example

Qt development tools include functionality for working with XML files, which allows you to create XML files and read them, which may be useful to create the automatic creation of XML markup software, configuration files, using XML, or for parsing XML-files .

To record in an XML file format used QXmlStreamWriter class, while the other is used QXmlStreamReader class to read an XML file.

The project structure for working with XML file

This project uses the minimum number of files:

  • XMLExample.pro - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source of window;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window;

mainwindow.ui

At this time in the form of the main window, you must add a sufficiently large number of items to make it look like this:

The main window of the application to work with an XML file

List of all the elements with which the work will be done in code:

  • checkBox - first checkbox;
  • checkBox_1 - the second Checkbox;
  • checkBox_2 - third checkbox;
  • lineEditCB1 - lineEdit for the first checkbox;
  • lineEditCB2 - lineEdit second checkbox;
  • lineEditCB3 - lineEdit for the third checkbox;
  • lineEditRead - lineEdit, which specifies the path to the file for reading;
  • lineEditWrite - lineEdit, which indicates the path to the file for writing;
  • dialogReadButton - button to call up the dialog to save the file in this case is simple file selection, which will be carried out the work;
  • dialogButton - button to call up the file recording the dialogue, in this case, the file is simply a choice, which will also be carried out work;
  • readButton - key performance reading from a file;
  • generateButton - button to record a file.

mainwindow.h

In the header file for the library connected with QXmlStreamWriter and QXmlStreamReader. Also announced slots handlers keystrokes.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QFileDialog>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QXmlStreamAttribute>
#include <QMessageBox>
#include <QFile>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    /* Slots handlers buttons which work with the record in the file */
    void on_generateButton_clicked();
    void on_dialogButton_clicked();

    /* Slots handlers buttons which work with the reading in the file */
    void on_readButton_clicked();
    void on_dialogReadButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

This source file reads and writes data into XML-file as well as the substitution of the parameters of the XML-file in the form of the main window.

#include "mainwindow.h"
#include "ui_mainwindow.h"
    
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
    
MainWindow::~MainWindow()
{
    delete ui;
}
   
/* The method performs recording of information in XML-file
 * */
void MainWindow::on_generateButton_clicked()
{
    /* Open the file for writing using the path specified in lineEditWrite */
    QFile file(ui->lineEditWrite->text());
    file.open(QIODevice::WriteOnly);

    /* Create an object, through which the recording to file */
    QXmlStreamWriter xmlWriter(&file);
    xmlWriter.setAutoFormatting(true);  // Set the auto-formatting text
    xmlWriter.writeStartDocument();     // run record in a document
    xmlWriter.writeStartElement("resources");   // Write the first element of his name

    xmlWriter.writeStartElement("checkBox_1");  // Write tag with the name for the first checkbox
    /* On the basis of the state of the checkbox attribute record "boolean" 
     * indicating the state of the checkbox in this attribute
     * */
    xmlWriter.writeAttribute("boolean",
                             (ui->checkBox->isChecked() ? "true" : "false"));
    /* We write in the body of this element from the corresponding line qlineEdit
     * */
    xmlWriter.writeCharacters(ui->lineEditCB1->text());
    xmlWriter.writeEndElement();        // Закрываем тег


    /* Repeat the same procedure for the other two checkboxes
     * */
    xmlWriter.writeStartElement("checkBox_2");
    xmlWriter.writeAttribute("boolean",
                             (ui->checkBox_2->isChecked() ? "true" : "false"));
    xmlWriter.writeCharacters(ui->lineEditCB2->text());
    xmlWriter.writeEndElement();

    xmlWriter.writeStartElement("checkBox_3");
    xmlWriter.writeAttribute("boolean",
                             (ui->checkBox_3->isChecked() ? "true" : "false"));
    xmlWriter.writeCharacters(ui->lineEditCB3->text());
    xmlWriter.writeEndElement();

    /* Close tag "resources"
     * */
    xmlWriter.writeEndElement();
    /* Finish the writing in the document
     * */
    xmlWriter.writeEndDocument();
    file.close();   // Закрываем файл
}
    
/* The method, which causes the file selection dialog box to save the data
 * */
void MainWindow::on_dialogButton_clicked()
{
    /* Call the file selection dialog to save */
    QString filename = QFileDialog::getSaveFileName(this,
                                           tr("Save Xml"), ".",
                                           tr("Xml files (*.xml)"));
    /* Set in lineEditWrite path to the file, with which we will work */
    if(filename != ""){
        ui->lineEditWrite->setText(filename);
    }
}
    
void MainWindow::on_readButton_clicked()
{
    /* Open the file for reading by using the path specified in lineEditWrite */
    QFile file(ui->lineEditRead->text());
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        QMessageBox::warning(this,
                             "Ошибка файла",
                             "Не удалось открыть файл",
                             QMessageBox::Ok);
    } else {
        /* Create an object, through which the reading of the file */
        QXmlStreamReader xmlReader;
        xmlReader.setDevice(&file);
        xmlReader.readNext();   // Moves to the first item in the file

        /* Work in a loop as long as we reach the end of the document
         * */
        while(!xmlReader.atEnd())
        {
            /* Check whether the beginning of the tag element
             * */
            if(xmlReader.isStartElement())
            {
                /* Check whether the tag refers to one of the checkboxes. 
                 * If "YES", then a check attribute checkbox and records for lineEdit
                 * */
                if(xmlReader.name() == "checkBox_1")
                {
                    /* Taking all of the tag attributes, 
                     * and through them to check for compliance with the required attribute to us
                     * */
                    foreach(const QXmlStreamAttribute &attr, xmlReader.attributes()) {
                        /* If the attribute is found, then its value is set the state of the checkbox
                         * */
                        if (attr.name().toString() == "boolean") {
                            QString attribute_value = attr.value().toString();
                            ui->checkBox->setChecked((QString::compare(attribute_value , "true") == 0) ? true : false);
    
                        }
                    }
                    /* pick up text from the body tag and paste it appropriate qlineEdit
                     * */
                    ui->lineEditCB1->setText(xmlReader.readElementText());

                    /* similar to working with other tags */
                } else if (xmlReader.name() == "checkBox_2"){
                    foreach(const QXmlStreamAttribute &attr, xmlReader.attributes()) {
                        if (attr.name().toString() == "boolean") {
                            QString attribute_value = attr.value().toString();
                            ui->checkBox_2->setChecked((QString::compare(attribute_value , "true") == 0) ? true : false);
    
                        }
                    }
                    ui->lineEditCB2->setText(xmlReader.readElementText());
                } else if (xmlReader.name() == "checkBox_3"){
                    foreach(const QXmlStreamAttribute &attr, xmlReader.attributes()) {
                        if (attr.name().toString() == "boolean") {
                            QString attribute_value = attr.value().toString();
                            ui->checkBox_3->setChecked((QString::compare(attribute_value , "true") == 0) ? true : false);
    
                        }
                    }
                    ui->lineEditCB3->setText(xmlReader.readElementText());
                }
            }
            xmlReader.readNext(); // Go to the next file element
        }
        file.close(); // Close the file
 
        /* This code is not checking for the closing tag because it is not necessary, 
         * but it allows the functional QXmlStreamReader
         * */
    }
}
    
/* The method, which causes the file selection dialog box to read the data
 * */
void MainWindow::on_dialogReadButton_clicked()
{
    /* Call the file selection dialog to read */
    QString filename = QFileDialog::getOpenFileName(this,
                                       tr("Open Xml"), ".",
                                       tr("Xml files (*.xml)"));
   /* Set in lineEditRead path to the file, which will work */
    if(filename != ""){
        ui->lineEditRead->setText(filename);
    }
}

As a result, we are able to create XML-file with the parameters and checkboxes our lineEdit types of objects, as well as to parse the file and set the data in the appropriate checkboxes and objects lineEdit.

The resulting file should be as follows:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <checkBox_1 boolean="false">XML</checkBox_1>
    <checkBox_2 boolean="false">Example</checkBox_2>
    <checkBox_3 boolean="true">EVILEG</checkBox_3>
</resources>

Result

As a result, should have the application that creates or rewrites the XML-file, taking data from the respective fields and checkboxes lineEdit, as well as producing the parsing of the XML-file data by setting the check boxes and fields lineEdit.

The application for working with XML files
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate
C

Не могли бы предоставить пример, где больше уровней в xml файле?

Это конечно можно, но насколько больше? И применительно к какому виду... Всё упирается же в то, куда именно будет этот XML применяться.

Например, чтение данных из XML можно сделать и с помощью QDomDocument. А если учесть, что SVG файл также фактически является XML документом, то Вы можете посмотреть следующий пример, для ознакомления с вытягиванием данных из XML файла:

SvgReader на Qt. Восстановление данных из файла SVG в QGraphicsScene

Comments

Only authorized users can post comments.
Please, Log in or Sign up
TT
June 13, 2019, 7:01 p.m.
Taimoor Tanweer

C++ - Test 001. The first program and data types

  • Result:66points,
  • Rating points-1
TT
June 13, 2019, 6:51 p.m.
Taimoor Tanweer

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
ВМ
June 13, 2019, 12:30 p.m.
Ваня Мороз

C++ - Test 001. The first program and data types

  • Result:100points,
  • Rating points10
Last comments
i
June 17, 2019, 6:10 a.m.
ingenfly

Только по осям xAxis2, уAxis2 значения начинаются с 0. Почему-то xAxis2 и xAxis не синхронизированы по данным. Ну и QCustomPlot последний.
June 16, 2019, 8:21 p.m.
Евгений Легоцкой

Добрый день. Ну точно также добавляете ту же самую информацию на ось xAxis2, только добавляете другое форматирование customPlot->xAxis2->setDateTimeFormat("hh:mm"); если я ...
EF
June 14, 2019, 1:56 p.m.
Egor Fomin

Спасибо за ваш ответ, у меня получилось реализовать это. Тем не менее появилась другая проблема, поэтому опять надеюсь на вашу помощь. Скажем, я уже выставил точки и они соеденены. Когда я нач...
d
June 13, 2019, 2:47 p.m.
damix

Можно классу, который описывает точку, добавить сигнал, который подавать (emit), когда точка перемещается (переопределить mouseMoveEvent или mouseReleaseEvent). Так вот эти сигналы у каждой из...
i
June 13, 2019, 2:09 p.m.
ingenfly

Здравствайте! Подскажите, пожалуйста: customPlot->xAxis2->setTickLabels(true); //Здесь включается отображение данных на оси xAxis2. а можно как-то продублировать информацию cus...
Now discuss on the forum
June 20, 2019, 9:30 a.m.
IscanderChe

Вернулся к этой задачке только-только, поэтому и не ответил ничего раньше.Как переопределить mouseReleaseEvent(QMouseEvent* event) у QTableView, если QTableView задан в ui? Или задавать QTabl...
I
June 19, 2019, 1:41 p.m.
Intruder

Всем добрый день. При разборе XML файла наткнулся на тег вот такого плана: <TagName attribute1="value1" attribute2="value2" /> При попытке проверить на наличие такого элеме...
June 19, 2019, 12:55 p.m.
Михаиллл

Скажите пожалуйста, как его в таком случае перемещать и удалять?
June 18, 2019, 7:50 p.m.
Дмитрий

Большое спасибо! SDK заработал.К сожалению удалось продвинутся только на один шаг. При сборке чистого проекта NDK выдаёт следующие ошибки C:\Android\ndk-bundle/toolchains/arm-linux-andr...
June 18, 2019, 4:59 p.m.
Михаиллл

Добрый день.В этом учебнике представлен код INSTALLED_APPS = ( ... 'rest_framework', 'snippets.apps.SnippetsConfig',) На строчке 'snippets.apps.SnippetsConf...
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB