Qt allows multiple ways to parse XML data, including the common method that we have covered in the previous examples. This time around, we're going to learn how to read data from an XML file using another class, called QDomDocument
.
Processing XML data using the QDomDocument
class is really simple:
.pro
) file and add the text xml
at the back of core
and gui
, like so:QT += core gui xml
clicked()
option. Press the OK button and Qt will add a slot function to your source code.mainwindow.h
and add the following headers so that we can make use of these classes:#include <QDomDocument> #include <QDebug> #include <QFile> #include <QFileDialog>
mainwindow.cpp
and insert the following code to the button's clicked()
slot function:Compared to QXmlStreamReader
, the QDomDocument
class is less straightforward when comes to loading or saving XML data. However, QDomDocument
does it in a strict way by making sure each element is linked to its respective parent element recursively, like in a tree structure. Unlike QXmlStreamReader
, QDomDocument
allows us to save data to an element created earlier, in a later timeframe.
Since QDomDocument
is not part of the Qt core library, we must add the XML module to our project manually. Otherwise, we will not be able to access QDomDocument
and other classes related to it.
First, we load the XML file and extract its content to the QDomDocument
class. Then, we get its document element, which acts as the root document, and obtain its direct children. We then convert each of the child nodes to QDomElement
and obtain their tag names.
By checking tag names, we are able to determine the type of data we're expecting from each element. Since this is the first layer of elements with the tag name object
, we don't expect any data from them; we repeat Step 3 again but this time around, we're going to do it on the element with the tag name object
and obtain all its direct children, which means the grandchildren of the document element.
Again, by checking the tag name, we're able to know what data we're expecting from its children elements. If the tag name matches the ones we're expecting (in this case, name
, position
, rotation
, scale
) then we can obtain its data by calling QDomElement::text()
.
3.133.142.2