BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Qt5 Tutorial QtXML DOM Reading - 2020





Bookmark and Share





bogotobogo.com site search:




QtXML Introduction

In this tutorial, we will learn how to read in QDOM of QtXML.


To include the definitions of the module's classes, use the following directive:

#include <QtXml>

To link against the module, add this line to our qmake .pro file:

QT += xml

Though the QtXML docuemnt says:

The module is not actively maintained anymore.
Please use the QXmlStreamReader and QXmlStreamWriter classes in Qt Core instead.

We still need to understand QtXML to move on to the other topics.




QtXML - reading from a file

In this example, we will read in from the following XML document we made in the previous tutorial: QtXML - Writing to a file.

<Dorms>
 <Dorm ID="0" Name="Dorm Building 0">
  <Room ID="0" Name="Room 0"/>
  <Room ID="1" Name="Room 1"/>
  <Room ID="2" Name="Room 2"/>
 </Dorm>
...
</Dorms>

To retrieve the info, the following code will be called by retrievElements(root, "Dorm", "Name").

void retrievElements(QDomElement root, QString tag, QString att)
{
    QDomNodeList nodes = root.elementsByTagName(tag);

    qDebug() << "# nodes = " << nodes.count();
    for(int i = 0; i < nodes.count(); i++)
    {
        QDomNode elm = nodes.at(i);
        if(elm.isElement())
        {
            QDomElement e = elm.toElement();
            qDebug() << e.attribute(att);
        }
    }
}

So, "Dorm" is for tag and "Name" is for attribute.

First, we get QDomNodeList using "Dorm" as tag by calling elementsByTagName(tag), then with that node, we get QDomElement using "Name" as an attribute for the call attribute(att).

The whole code looks like this:

#include <QtCore>
#include <QtXML>
#include <QDebug>

void retrievElements(QDomElement root, QString tag, QString att)
{
    QDomNodeList nodes = root.elementsByTagName(tag);

    qDebug() << "# nodes = " << nodes.count();
    for(int i = 0; i < nodes.count(); i++)
    {
        QDomNode elm = nodes.at(i);
        if(elm.isElement())
        {
            QDomElement e = elm.toElement();
            qDebug() << e.attribute(att);
        }
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create a document to write XML
    QDomDocument document;

    // Open a file for reading
    QFile file("C:/Test/myXLM.xml");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Failed to open the file for reading.";
        return -1;
    }
    else
    {
        // loading
        if(!document.setContent(&file;))
        {
            qDebug() << "Failed to load the file for reading.";
            return -1;
        }
        file.close();
    }

    // Getting root element
    QDomElement root = document.firstChildElement();

    // retrievelements(QDomElement root, QString tag, QString att)
    retrievElements(root, "Dorm", "Name");

    qDebug() << "Reading finished";

    return a.exec();
}

If we run the code now, we get:

# nodes =  5
"Dorm Building 0"
"Dorm Building 1"
"Dorm Building 2"
"Dorm Building 3"
"Dorm Building 4"
Reading finished

We get the 2nd level element but the the 3rd level element ("Room") yet.

    // Getting root element
    QDomElement root = document.firstChildElement();

    // retrievelements(QDomElement root, QString tag, QString att)
    retrievElements(root, "Dorm", "Name");

    qDebug() << "\nGoing deeper level - getting the 'Room'";
    QDomNodeList dorms = root.elementsByTagName("Dorm");
    // Looping through each dorm
    for(int i = 0; i < dorms.count(); i++)
    {
        QDomNode dormnode = dorms.at(i);
        if(dormnode.isElement())
        {
            QDomElement dorm = dormnode.toElement();
            qDebug() << "Rooms in " << dorm.attribute("Name");
            /*
             *-<Dorm Name="Dorm Building 0" ID="0">
             *   <Room Name="Room 0" ID="0"/>
             *   <Room Name="Room 1" ID="1"/>
             *   <Room Name="Room 2" ID="2"/>
             */
            retrievElements(dorm, "Room", "Name");
        }
    }

Run the code, and we get:

# nodes =  5
"Dorm Building 0"
"Dorm Building 1"
"Dorm Building 2"
"Dorm Building 3"
"Dorm Building 4"

Going deeper level - getting the 'Room'
Rooms in  "Dorm Building 0"
# nodes =  3
"Room 0"
"Room 1"
"Room 2"
Rooms in  "Dorm Building 1"
# nodes =  3
"Room 0"
"Room 1"
"Room 2"
Rooms in  "Dorm Building 2"
# nodes =  3
"Room 0"
"Room 1"
"Room 2"
Rooms in  "Dorm Building 3"
# nodes =  3
"Room 0"
"Room 1"
"Room 2"
Rooms in  "Dorm Building 4"
# nodes =  3
"Room 0"
"Room 1"
"Room 2"
Reading finished



Source Code

Get the source code: main.cpp.

or
#include <QtCore>
#include <QtXML>
#include <QDebug>

void retrievElements(QDomElement root, QString tag, QString att)
{
    QDomNodeList nodes = root.elementsByTagName(tag);

    qDebug() << "# nodes = " << nodes.count();
    for(int i = 0; i < nodes.count(); i++)
    {
        QDomNode elm = nodes.at(i);
        if(elm.isElement())
        {
            QDomElement e = elm.toElement();
            qDebug() << e.attribute(att);
        }
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create a document to write XML
    QDomDocument document;

    // Open a file for reading
    QFile file("C:/Test/myXLM.xml");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Failed to open the file for reading.";
        return -1;
    }
    else
    {
        // loading
        if(!document.setContent(&file;))
        {
            qDebug() << "Failed to load the file for reading.";
            return -1;
        }
        file.close();
    }

    // Getting root element
    QDomElement root = document.firstChildElement();

    // retrievelements(QDomElement root, QString tag, QString att)
    retrievElements(root, "Dorm", "Name");

    qDebug() << "\nGoing deeper level - getting the 'Room'";
    QDomNodeList dorms = root.elementsByTagName("Dorm");
    // Looping through each dorm
    for(int i = 0; i < dorms.count(); i++)
    {
        QDomNode dormnode = dorms.at(i);
        if(dormnode.isElement())
        {
            QDomElement dorm = dormnode.toElement();
            qDebug() << "Rooms in " << dorm.attribute("Name");
            /*
             *-<Dorm Name="Dorm Building 0" ID="0">
             *   <Room Name="Room 0" ID="0"/>
             *   <Room Name="Room 1" ID="1"/>
             *   <Room Name="Room 2" ID="2"/>
             */
            retrievElements(dorm, "Room", "Name");
        }
    }

    qDebug() << "Reading finished";

    return a.exec();
}











Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Qt 5 Tutorial



Hello World

Signals and Slots

Q_OBJECT Macro

MainWindow and Action

MainWindow and ImageViewer using Designer A

MainWindow and ImageViewer using Designer B

Layouts

Layouts without Designer

Grid Layouts

Splitter

QDir

QFile (Basic)

Resource Files (.qrc)

QComboBox

QListWidget

QTreeWidget

QAction and Icon Resources

QStatusBar

QMessageBox

QTimer

QList

QListIterator

QMutableListIterator

QLinkedList

QMap

QHash

QStringList

QTextStream

QMimeType and QMimeDatabase

QFile (Serialization I)

QFile (Serialization II - Class)

Tool Tips in HTML Style and with Resource Images

QPainter

QBrush and QRect

QPainterPath and QPolygon

QPen and Cap Style

QBrush and QGradient

QPainter and Transformations

QGraphicsView and QGraphicsScene

Customizing Items by inheriting QGraphicsItem

QGraphicsView Animation

FFmpeg Converter using QProcess

QProgress Dialog - Modal and Modeless

QVariant and QMetaType

QtXML - Writing to a file

QtXML - QtXML DOM Reading

QThreads - Introduction

QThreads - Creating Threads

Creating QThreads using QtConcurrent

QThreads - Priority

QThreads - QMutex

QThreads - GuiThread

QtConcurrent QProgressDialog with QFutureWatcher

QSemaphores - Producer and Consumer

QThreads - wait()

MVC - ModelView with QListView and QStringListModel

MVC - ModelView with QTreeView and QDirModel

MVC - ModelView with QTreeView and QFileSystemModel

MVC - ModelView with QTableView and QItemDelegate

QHttp - Downloading Files

QNetworkAccessManager and QNetworkRequest - Downloading Files

Qt's Network Download Example - Reconstructed

QNetworkAccessManager - Downloading Files with UI and QProgressDialog

QUdpSocket

QTcpSocket

QTcpSocket with Signals and Slots

QTcpServer - Client and Server

QTcpServer - Loopback Dialog

QTcpServer - Client and Server using MultiThreading

QTcpServer - Client and Server using QThreadPool

Asynchronous QTcpServer - Client and Server using QThreadPool

Qt Quick2 QML Animation - A

Qt Quick2 QML Animation - B

Short note on Ubuntu Install

OpenGL with QT5

Qt5 Webkit : Web Browser with QtCreator using QWebView Part A

Qt5 Webkit : Web Browser with QtCreator using QWebView Part B

Video Player with HTML5 QWebView and FFmpeg Converter

Qt5 Add-in and Visual Studio 2012

Qt5.3 Installation on Ubuntu 14.04

Qt5.5 Installation on Ubuntu 14.04

Short note on deploying to Windows




Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong













Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master