Writing XML data using the QDomDocument class

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.

How to do it…

To learn how to save data into an XML file using the QDomDocument class, let's do the following:

  1. First of all, add the second button to the UI, called Save XML:
    How to do it…
  2. Right-click on the Save XML button and select Go to slot…. Then, pick the clicked() option and click OK. A new clicked() slot function will now be added to your source files.
  3. After that, write the following code within the button's clicked() slot function:
    How to do it…
    How to do it…
  4. Compile and run the program now and click on the Save XML button. Enter your desired filename in the save file dialog and click Save.
  5. Open up the XML file you just saved in Step 4 with any text editor and you should see something like this:
    <!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>

How it works…

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.

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

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