In this example, we will learn how to write data to an XML file using the QDomDocument
class. We will continue from the previous example and just add stuff to it.
To learn how to save data into an XML file using the QDomDocument
class, let's do the following:
clicked()
slot function will now be added to your source files.clicked()
slot function:<!DOCTYPE contact> <contact category="Family"> <name>John Doe</name> <age>32</age> <address>114B, 2nd Floor, Sterling Apartment, Morrisontown</address> <phone>0221743566</phone> </contact> <contact category="Friend"> <name>John Doe</name> <age>32</age> <address>114B, 2nd Floor, Sterling Apartment, Morrisontown</address> <phone>0221743566</phone> </contact>
Similar to the previous example, we first initiate the file dialog and declare a QDomDocument
object.
Then, we create the root element by calling QDomDocument::createElement()
. Any element created from the QDomDocument
will NOT automatically become its direct child unless we append the newly created element as its child.
To create the grandchildren of QDomDocument
, simply append the newly created elements to the root element instead. By utilizing the append()
function, we can easily arrange the XML data in a tree structure without wrapping our head around it. This, in my opinion, is the advantage of using QDomDocument
instead of QXmlStreamReader
.
We can then add attributes to an element by calling QDomElement::setAttribute()
. We can also create a text node by calling QDomDocument::createTextNode()
and appending it to any of the elements in the XML structure.
After we are done structuring the XML data, we can then output all the data in the form of text to the QTextStream
class and allow it to save the data into a file.
3.129.210.102