We will learn how to save data into an XML file through the following steps:
- Add another button to mainwindow.ui, then set its object name as saveXmlButton and its label as Save XML:
- Right-click on the button and select Go to slot…. A window will pop up with a list of signals available for selection. Select the clicked() option and click OK. A signal function called on_saveXmlButton_clicked() will now be automatically added to both your mainwindow.h and mainwindow.cpp files by Qt:
- Add the following code to the on_saveXmlButton_clicked() function:
QXmlStreamWriter xml;
QString filename = QFileDialog::getSaveFileName(this, "Save Xml", ".", "Xml files (*.xml)");
QFile file(filename);
if (!file.open(QFile::WriteOnly | QFile::Text))
qDebug() << "Error saving XML file.";
xml.setDevice(&file);
xml.setAutoFormatting(true);
xml.writeStartDocument();
- Let's also write the first contact element:
xml.writeStartElement("contact");
xml.writeAttribute("category", "Friend");
xml.writeTextElement("name", "John Doe");
xml.writeTextElement("age", "32");
xml.writeTextElement("address", "114B, 2nd Floor, Sterling Apartment, Morrison Town");
xml.writeTextElement("phone", "0221743566");
xml.writeEndElement();
- Write the second contact element as follows:
xml.writeStartElement("contact");
xml.writeAttribute("category", "Family");
xml.writeTextElement("name", "Jane Smith");
xml.writeTextElement("age", "24");
xml.writeTextElement("address", "13, Ave Park, Alexandria");
xml.writeTextElement("phone", "0025728396");
xml.writeEndElement();
xml.writeEndDocument();
- Build and run the program and you should see an additional button on the program UI:
- Click on the Save XML button and a save file dialog will appear on the screen. Type the filename you desire and click the Save button.
- Open up the XML file you just saved with any text editor. The first part of the file should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<contact category="Friend">
<name>John Doe</name>
<age>32</age>
<address>114B, 2nd Floor, Sterling Apartment, Morrison Town</address>
<phone>0221743566</phone>
</contact>
- The second part of the file should look something like this:
<contact category="Family">
<name>Jane Smith</name>
<age>24</age>
<address>13, Ave Park, Alexandria</address>
<phone>0025728396</phone>
</contact>