How to do it…

Processing XML data using the QDomDocument class is really simple:

  1. Add the XML module to the project by opening the project (.pro) file and adding the xml text after core and gui, as shown in the following code:
QT += core gui xml
  1. Create a user interface that carries a button that says Load XML:

  1. Right-click on the button, choose Go to slot…, and select the clicked() option. Press the OK button and Qt will add a slot function to your source code.
  2. Go to mainwindow.h and add the following headers so that we can make use of these classes:
#include <QDomDocument>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
  1. Go to mainwindow.cpp and insert the following code to the button's clicked() slot function:
void MainWindow::on_loadXmlButton_clicked() {
QDomDocument xml;
QString filename = QFileDialog::getOpenFileName(this, "Open Xml", ".", "Xml files (*.xml)");
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text))
qDebug() << "Error loading XML file.";
if (!xml.setContent(&file)) {
qDebug() << "Error setting content.";
file.close();
return;
}
file.close();
  1. We continue to write the code to load XML:
QDomElement element = xml.documentElement();
QDomNode node = element.firstChild();
while(!node.isNull()) {
QDomElement nodeElement = node.toElement();
if(!nodeElement.isNull()) {
if (nodeElement.tagName() == "object") {
qDebug() << "[Object]=================================";
QDomNode childNode = nodeElement.firstChild();
  1. The previous code continues as follows:
                while (!childNode.isNull()) {
QDomElement childNodeElement = childNode.toElement();
QString name = childNodeElement.tagName();
if (name=="name" || name=="position" || name=="rotation" || name=="scale") {
QString text = childNodeElement.text();
qDebug() << name << text;
}
childNode = childNode.nextSibling();
}
}
qDebug() << "=========================================";
}
node = node.nextSibling();
}
}
  1. Compile and run the program. Click on the Load XML button and select the XML file used in the first example. You should see the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset