How to Read and Write XML files in QT C++

How to Read and Write XML files in QT C++

Hello everyone, in this article we are going to read and write XML files with using QT C++. We will make an example about management of XML datas in QT C++.

Let's begin.

We can write and read XML files to store some datas in an XML file to use later. In qt we can perform this operations with QtXML library.

Firstly we need to add below row into .pro file of the project.

QT += xml
Now we need to include below two libraries in our header.

#include <QtXml>
#include <QTextStream>
  • QtXml will let us to manage the XML operations with QtXml.
  • QTextStream will let us to read and write XML file which store the datas.

Now we let's create XML elements and load datas in it. Then write them into file.

Below code block will create an XML file and write XML data in created file.

void XmlExample::writeXMLFile(){
    QFile xmlFile("xmlSample.xml");
    if (!xmlFile.open(QFile::WriteOnly | QFile::Text ))
    {
        qDebug() << "Already opened or there is another issue";
        xmlFile.close();
    }
    QTextStream xmlContent(&xmlFile);

    QDomDocument document;

    //make the root element
    QDomElement root = document.createElement("StudentList");
    //add it to document
    document.appendChild(root);

    QDomElement student = document.createElement("student");
    student.setAttribute("id", "1");
    student.setAttribute("name", "Burak");
    student.setAttribute("number", "1111");
    root.appendChild(student);

    student = document.createElement("student");
    student.setAttribute("id", "2");
    student.setAttribute("name", "Hamdi");
    student.setAttribute("number", "2222");
    root.appendChild(student);

    student = document.createElement("student");
    student.setAttribute("id", "3");
    student.setAttribute("name", "TUFAN");
    student.setAttribute("number", "33333");
    root.appendChild(student);

    student = document.createElement("student");
    student.setAttribute("id", "4");
    student.setAttribute("name", "Thecodeprogram");
    student.setAttribute("number", "4444");
    root.appendChild(student);

    xmlContent << document.toString();
}

What have we done in writing method :

  • Firstly we controlled the XML file and if there is no problem we opened than set it to xmlContent.
  • Then we create an XML document with QDomDocument. We are going to create nodes under this document.
  • Then we created our root element with QDomElement. We appended root element to our document. Because we want our root element directly under the document.
  • Then we created other elements under root element. For appending sub nodes to root node we used root.appendChild(...); method.
  • Lastly we wrote all XML data inside an XML file with xmlContent << document.toString(). We created xmlContent variable at the head of method with a QTextStream.
Below image you can see the content of XML File: XML Writing example output - Thecodeprogram

Now let's read the XML file which we have written above.

Below code you will see the reading XML file:

void XmlExample::loadXMLFile(){
    QDomDocument studentsXML;
    QFile xmlFile("xmlSample.xml");
    if (!xmlFile.open(QIODevice::ReadOnly ))
    {
        // Error while loading file
    }
    studentsXML.setContent(&xmlFile);
    xmlFile.close();

    QDomElement root = studentsXML.documentElement();
    QDomElement node = root.firstChild().toElement();

    QString datas = "";

    while(node.isNull() == false)
    {
        qDebug() << node.tagName();
        if(node.tagName() == "student"){
            while(!node.isNull()){
                QString id = node.attribute("id","0");
                QString name = node.attribute("name","name");
                QString number = node.attribute("number","number");

                datas.append(id).append(" - ").append(name).append(" - ").append(number).append("\n");
                node = node.nextSibling().toElement();
            }
        }
        node = node.nextSibling().toElement();
    }
    ui->txtLoadedXmlContent->setPlainText(datas);
}

What have we done in reading method :

  • Firstly we read the related XML file and loaded into QDomDocument to parse content data.
  • Then we created QDomElement and readed first child node. In here we assumed there is only one root node and all sub nodes inside this root node.
  • Then we started to read nodes inside root node. We set the tag name as student and we assigned related datas into attributes to. (I like to use attributes instead of sub nodes if not necessary)
  • In while loop we are traversing all of nodes until find the null one. It means we traverse all nodes.
  • And lastly I showed the datas inside a textbox.
Below image you can see the example output of reading. XML Reading XML file in QT C++ - Thecodeprogram

That is all in this article.

Have a good XML management.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...