Qt Xml Read Write Example Essay

On By In 1

This chapter covers the QtXml module, which Qt provides for general XML processing.

This chapter is from the book 

16. XML

  • Reading XML with QXmlStreamReader
  • Reading XML with DOM
  • Reading XML with SAX
  • Writing XML

XML (eXtensible Markup Language) is a general-purpose text file format that is popular for data interchange and data storage. It was developed by the World Wide Web Consortium (W3C) as a lightweight alternative to SGML (Standard Generalized Markup Language). The syntax is similar to HTML, but XML is a metalanguage and as such does not mandate specific tags, attributes, or entities. The XML-compliant version of HTML is called XHTML.

For the popular SVG (Scalable Vector Graphics) XML format, the QtSvg module provides classes that can load and render SVG images. For rendering documents that use the MathML (Mathematical Markup Language) XML format, the from Qt Solutions can be used.

For general XML processing, Qt provides the QtXml module, which is the subject of this chapter. [*] The QtXml module offers three distinct APIs for reading XML documents:

  • is a fast parser for reading well-formed XML.
  • DOM (Document Object Model) converts an XML document into a tree structure, which the application can then navigate.
  • SAX (Simple API for XML) reports "parsing events" directly to the application through virtual functions.

The class is the fastest and easiest to use and offers an API that is consistent with the rest of Qt. It is ideal for writing one-pass parsers. DOM's main benefit is that it lets us navigate a tree representation of the XML document in any order, allowing us to implement multi-pass parsing algorithms. Some applications even use the DOM tree as their primary data structure. SAX is provided mainly for historical reasons; using usually leads to simpler and faster code.

For writing XML files, Qt also offers three options:

  • We can use a .
  • We can represent the data as a DOM tree in memory and ask the tree to write itself to a file.
  • We can generate the XML by hand.

Using is by far the easiest approach, and is more reliable than hand-generating XML. Using DOM to produce XML really makes sense only if a DOM tree is already used as the application's primary data structure. All three approaches to reading and writing XML are shown in this chapter.

Reading XML with QXmlStreamReader

Using is the fastest and easiest way to read XML in Qt. Because the parser works incrementally, it is particularly useful for finding all occurrences of a given tag in an XML document, for reading very large files that may not fit in memory, and for populating custom data structures to reflect an XML document's contents.

The parser works in terms of the tokens listed in Figure 16.1. Each time the function is called, the next token is read and becomes the current token. The current token's properties depend on the token's type and are accessible using the getter functions listed in the table.

Table 16.1. The 's tokens

Token Type

Example

Getter Functions

N/A

N/A

,,,

,

,,

,,

,

,

,

Consider the following XML document:

<doc> <quote>Einmal ist keinmal</quote> </doc>

If we parse this document, each call will produce a new token, with extra information available using getter functions:

StartDocument StartElement (name() == "doc") StartElement (name() == "quote") Characters (text() == "Einmal ist keinmal") EndElement (name() == "quote") EndElement (name() == "doc") EndDocument

After each call, we can test for the current token's type using , , and similar functions, or simply using .

We will review an example that shows how to use to parse an ad hoc XML file format and render its contents in a . The format we will parse is that of a book index, with index entries and sub-entries. Here's the book index file that is displayed in the in Figure 16.2:

<?xml version="1.0"?> <bookindex> <entry term="sidebearings"> <page>10</page> <page>34-35</page> <page>307-308</page> </entry> <entry term="subtraction"> <entry term="of pictures"> <page>115</page> <page>244</page> </entry> <entry term="of vectors"> <page>9</page> </entry> </entry> </bookindex>

We will begin by looking at an extract from the application's function, to see how the XML reader is used in context, and then we will look at the reader's implementation.

int main(int argc, char *argv[]) { QApplication app(argc, argv); QStringList args = QApplication::arguments(); ... QTreeWidget treeWidget; ... XmlStreamReader reader(&treeWidget); for (int i = 1; i < args.count(); ++i) reader.readFile(args[i]); return app.exec(); }

The application shown in Figure 16.2 begins by creating a . It then creates an , passing it the tree widget and asking it to parse each file specified on the command line.

class XmlStreamReader { public: XmlStreamReader(QTreeWidget *tree); bool readFile(const QString &fileName); private: void readBookindexElement(); void readEntryElement(QTreeWidgetItem *parent); void readPageElement(QTreeWidgetItem *parent); void skipUnknownElement(); QTreeWidget *treeWidget; QXmlStreamReader reader; };

The class provides two public functions: the constructor and . The class uses a instance to parse the XML file, and populates the to reflect the XML data that is read. The parsing is done using recursive descent:

  • parses a element that contains zero or more elements.
  • parses an element that contains zero or more elements and zero or more elements nested to any depth.
  • parses a element.
  • skips an unrecognized element.

We will now look at the class's implementation, beginning with the constructor.

XmlStreamReader::XmlStreamReader(QTreeWidget *tree) { treeWidget = tree; }

The constructor is used only to establish which the reader should use. All the action takes place in the function (called from ), which we will look at in three parts.

bool XmlStreamReader::readFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { std::cerr << "Error: Cannot read file " << qPrintable(fileName) << ": " << qPrintable(file.errorString()) << std::endl; return false; } reader.setDevice(&file);

The function begins by trying to open the file. If it fails, it outputs an error message and returns . If the file is opened successfully, it is set as the 's input device.

reader.readNext(); while (!reader.atEnd()) { if (reader.isStartElement()) { if (reader.name() == "bookindex") { readBookindexElement(); } else { reader.raiseError(QObject::tr("Not a bookindex file")); } } else { reader.readNext(); } }

The 's function reads the next token from the input stream. If a token is successfully read and the end of the XML file has not been reached, the function enters the loop. Because of the structure of the index files, we know that inside this loop there are just three possibilities: A start tag has just been read, another start tag has been read (in which case the file is not a book index), or some other token has been read.

If we have the correct start tag, we call to continue processing. Otherwise, we call with an error message. The next time is called (in the loop condition), it will return . This ensures that parsing stops as soon as possible after an error has been encountered. The error can be queried later by calling and on the . An alternative would have been to return right away when we detect an error in the book index file. Using is usually more convenient, because it lets us use the same error-reporting mechanism for low-level XML parsing errors, which are raised automatically when runs into invalid XML, and for application-specific errors.

file.close(); if (reader.hasError()) { std::cerr << "Error: Failed to parse file " << qPrintable(fileName) << ": " << qPrintable(reader.errorString()) << std::endl; return false; } else if (file.error() != QFile::NoError) { std::cerr << "Error: Cannot read file " << qPrintable(fileName) << ": " << qPrintable(file.errorString()) << std::endl; return false; } return true; }

Once the processing has finished, the file is closed. If there was a parser error or a file error, the function outputs an error message and returns ; otherwise, it returns to report a successful parse.

void XmlStreamReader::readBookindexElement() { reader.readNext(); while (!reader.atEnd()) { if (reader.isEndElement()) { reader.readNext(); break; } if (reader.isStartElement()) { if (reader.name() == "entry") { readEntryElement(treeWidget->invisibleRootItem()); } else { skipUnknownElement(); } } else { reader.readNext(); } } }

The is responsible for reading the main part of the file. It starts by skipping the current token (which at this point can be only a start tag) and then loops over the input.

If an end tag is read, it can be only the tag, since otherwise, would have reported an error (). In that case, we skip the tag and break out of the loop. Otherwise, we should have a top-level index start tag. If this is the case, we call to process the entry's data; if not, we call . Using rather than calling means that if we extend the book index format in the future to include new tags, this reader will continue to work, since it will simply ignore the tags it does not recognize.

The takes a argument that identifies a parent item. We pass as the parent to make the new items root items. In , we will call recursively, with a different parent.

void XmlStreamReader::readEntryElement(QTreeWidgetItem *parent) { QTreeWidgetItem *item = new QTreeWidgetItem(parent); item->setText(0, reader.attributes().value("term").toString()); reader.readNext(); while (!reader.atEnd()) { if (reader.isEndElement()) { reader.readNext(); break; } if (reader.isStartElement()) { if (reader.name() == "entry") { readEntryElement(item); } else if (reader.name() == "page") { readPageElement(item); } else { skipUnknownElement(); } } else { reader.readNext(); } } }

The function is called whenever an start tag is encountered. We want a tree widget item to be created for every index entry, so we create a new , and set its first column's text to be the entry's term attribute's text.

Once the entry has been added to the tree, the next token is read. If it is an end tag, we skip the tag and break out of the loop. If a start tag is encountered, it will be an tag (signifying a sub-entry), a tag (a page number for this entry), or an unknown tag. If the start tag is a sub-entry, we call recursively. If the tag is a tag, we call .

void XmlStreamReader::readPageElement(QTreeWidgetItem *parent) { QString page = reader.readElementText(); if (reader.isEndElement()) reader.readNext(); QString allPages = parent->text(1); if (!allPages.isEmpty()) allPages += ", "; allPages += page; parent->setText(1, allPages); }

The function is called whenever we get a tag. It is passed the tree item that corresponds to the entry to which the page text belongs. We begin by reading the text between the and tags. On success, the function will leave the parser on the tag, which we must skip.

The pages are stored in the tree widget item's second column. We begin by extracting the text that is already there. If the text is not empty, we append a comma to it, ready for the new page text. We then append the new text and update the column's text accordingly.

void XmlStreamReader::skipUnknownElement() { reader.readNext(); while (!reader.atEnd()) { if (reader.isEndElement()) { reader.readNext(); break; } if (reader.isStartElement()) { skipUnknownElement(); } else { reader.readNext(); } } }

Finally, when unknown tags are encountered, we keep reading until we get the unknown element's end tag, which we also skip. This means that we will skip over well-formed but unrecognized elements, and read as much of the recognizable data as possible from the XML file.

The example presented here could be used as the basis for similar XML recursive descent parsers. Nonetheless, sometimes implementing a parser like this can be tricky, if a call is missing or out of place. Some programmers address the problem by using assertions in their code. For example, at the beginning of , we could add the line

Q_ASSERT(reader.isStartElement() && reader.name() == "bookindex");

A similar assertion could be made in the and functions. For , we would simply assert that we have a start element.

A can take input from any , including , , , and . Some input sources may not be able to provide the data that the parser needs when it needs it—for example, due to network latency. It is still possible to use under such circumstances; more information on this is provided in the reference documentation for under the heading "Incremental Parsing".

The class used in this application is part of the QtXml library. To link against this library, we must add this line to the file:

QT += xml

In the next two sections, we will see how to write the same application with DOM and SAX.

Qt5 Tutorial QtXML - 2018




bogotobogo.com site search:





QtXML Introduction

In this tutorial, we will learn about QtXML.


To include the definitions of the module's classes, use the following directive:

#include <QtXml>

To link against the module, add this line to our qmake .pro file:

QT += xml

Though the QtXML docuemnt says:

The module is not actively maintained anymore.
Please use the QXmlStreamReader and QXmlStreamWriter classes in Qt Core instead.

We still need to understand QtXML to move on to the other topics.




QtXML - writing to a file

In this example, we will write a XML document.

#include <QtCore> #include <QtXML> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Create a document to write XML QDomDocument document; // Making the root element QDomElement root = document.createElement("Dorms"); // Adding the root element to the docuemnt document.appendChild(root); // Writing to a file QFile file("C:/Test/myXLM.xml"); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Open the file for writing failed"; } else { QTextStream stream(&file;); stream << document.toString(); file.close(); qDebug() << "Writing is done"; } return a.exec(); }

First, we need to create a document:

QDomDocument document;

Then, make a root element and attach it to the document:

// Making the root element QDomElement root = document.createElement("Dorms"); // Adding the root element to the docuemnt document.appendChild(root);

Then, open a file and start to writng using QTextStream:

QTextStream stream(&file;); stream << document.toString();

We can open the XML document to see using XML editor:

<?xml version="1.0"?> <Dorms/>

If we add child elements:

// Adding the root element to the docuemnt document.appendChild(root); // Adding more elements for(int i = 0; i < 5; i++) { QDomElement dorm = document.createElement("Dorm"); dorm.setAttribute("Name", "Dorm Building " + QString::number(i)); dorm.setAttribute("ID", QString::number(i)); root.appendChild(dorm); }

Open the XML doc:

<Dorms> <Dorm ID="0" Name="Dorm Building 0"/> <Dorm ID="1" Name="Dorm Building 1"/> <Dorm ID="2" Name="Dorm Building 2"/> <Dorm ID="3" Name="Dorm Building 3"/> <Dorm ID="4" Name="Dorm Building 4"/> </Dorms>

Now, we want to put rooms to each dorm building:

document.appendChild(root); // Adding more elements for(int i = 0; i < 5; i++) { QDomElement dorm = document.createElement("Dorm"); dorm.setAttribute("Name", "Dorm Building " + QString::number(i)); dorm.setAttribute("ID", QString::number(i)); root.appendChild(dorm); // Adding rooms to each dorm building for(int j = 0; j < 3; j++) { QDomElement room = document.createElement("Room"); room.setAttribute("Name", "Room " + QString::number(j)); room.setAttribute("ID", QString::number(j)); dorm.appendChild(room); } }

Indeed, each Dorm building has rooms now:

<Dorms> <Dorm ID="0" Name="Dorm Building 0"> <Room ID="0" Name="Room 0"/> <Room ID="1" Name="Room 1"/> <Room ID="2" Name="Room 2"/> </Dorm> <Dorm ID="1" Name="Dorm Building 1"> <Room ID="0" Name="Room 0"/> <Room ID="1" Name="Room 1"/> <Room ID="2" Name="Room 2"/> </Dorm> <Dorm ID="2" Name="Dorm Building 2"> <Room ID="0" Name="Room 0"/> <Room ID="1" Name="Room 1"/> <Room ID="2" Name="Room 2"/> </Dorm> <Dorm ID="3" Name="Dorm Building 3"> <Room ID="0" Name="Room 0"/> <Room ID="1" Name="Room 1"/> <Room ID="2" Name="Room 2"/> </Dorm> <Dorm ID="4" Name="Dorm Building 4"> <Room ID="0" Name="Room 0"/> <Room ID="1" Name="Room 1"/> <Room ID="2" Name="Room 2"/> </Dorm> </Dorms>

Source Code

Here is the final version of source code, main.cpp.

or #include <QtCore> #include <QtXML> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Create a document to write XML QDomDocument document; // Making the root element QDomElement root = document.createElement("Dorms"); // Adding the root element to the docuemnt document.appendChild(root); // Adding more elements for(int i = 0; i < 5; i++) { QDomElement dorm = document.createElement("Dorm"); dorm.setAttribute("Name", "Dorm Building " + QString::number(i)); dorm.setAttribute("ID", QString::number(i)); root.appendChild(dorm); // Adding rooms to each dorm building for(int j = 0; j < 3; j++) { QDomElement room = document.createElement("Room"); room.setAttribute("Name", "Room " + QString::number(j)); room.setAttribute("ID", QString::number(j)); dorm.appendChild(room); } } // Writing to a file QFile file("C:/Test/myXLM.xml"); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Open the file for writing failed"; } else { QTextStream stream(&file;); stream << document.toString(); file.close(); qDebug() << "Writing is done"; } return a.exec(); }






Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong



0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *