How it works…

In this example, we're trying to extract and process data from an XML file using the QXmlStreamReader class. Imagine you're making a computer game and you're using XML files to store the attributes of all the objects in your game scene. In this case, the XML format plays an important role in storing the data in a structured way, which allows for easy extraction.

We need to add the header of the class related to XML to our source file, which in this case is the QXmlStreamReader class. The QXmlStreamReader class is built into Qt's core library, so there is no need to include any additional modules with it, which also means that it's the recommended class to use to process XML data in Qt. Once we click on the Load XML button, the on_loadXmlButton_clicked() slot will be called; this is where we write the code to process the XML data.

We use a file dialog to select the XML file we want to process. Then we send the selected file's filename, together with its path, to the QFile class to open and read the text data of the XML file. After that, the file's data is sent to the QXmlStreamReader class for processing.

We use a while loop to read through the entire XML file and check every element processed by the stream reader. We determine whether the element is a start element or an end element. If it's a start element, we check the name of the element to determine whether the element should contain any data that we need.

Then, we extract the data, either in the form of an attribute or text. An element may have more than one attribute, which is why we must loop through all the attributes and extract them one by one.

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

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