How it works…

The saving process is similar to loading an XML file in the previous example. The only difference is instead of using the QXmlStreamReader class, we switched to using the QXmlStreamWriter class. We are still using the file dialog and the QFile class to save the XML file. This time, we have to change the open mode from QFile::ReadOnly to QFile::WriteOnly before passing the QFile class to the Stream Writer.

Before we start writing any data to the new XML file, we must set auto-formatting to true, otherwise there will be no spacing; it also adds new lines and indentation to the XML file to make it tidy and easier to read. However, if your intention is to make it harder to read and edit by the user, you can just ignore the setAutoFormatting() function.

Next, start writing the XML file by calling writeStartDocument(), followed by all the elements you want to save to the file, and at the end we call the writeEndDocument() function to stop writing. Each element must have start and end tags in order for the reading process to work properly. The attributes of an element will be stored in the start tag, while the text data will be stored between the start and end tags.

If we're writing an element that contains a group of child elements, we must call writeStartElement() before writing the child elements. Call writeEndElement() after saving all its child elements to close the group with an end tag. The writetextElement() function, however, will automatically add the end tag for you, so you don't have to worry about that one. You can call the writeAttribute() function to add an attribute to an element. There is no limit on how many attributes you can add to a particular element.

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

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