- Qt 6.9
- Qt XML
- XML Streaming
- Qt 6.9.3 Reference Documentation

An Introduction to Namespaces ◦ Working with the DOM Tree

# XML Streaming

Qt provides two classes for reading and writing XML through a simple streaming API: QXmlStreamReader and QXmlStreamWriter. These classes are located in Qt Serialization (part of QtCore).

A stream reader reports an XML document as a stream of tokens. This differs from SAX as SAX applications provide handlers to receive XML events from the parser whereas the QXmlStreamReader drives the loop, pulling tokens from the reader when they are needed. This pulling approach makes it possible to build recursive descent parsers, allowing XML parsing code to be split into different methods or classes.

QXmlStreamReader is a well-formed XML 1.0 parser that excludes external parsed entities. Hence, data provided by the stream reader adheres to the W3C's criteria for well-formed XML, as long as no error occurs. Otherwise, functions such as atEnd(), error() and hasError() can be used to check and view the errors.

An example of an implementation tha uses QXmlStreamReader would be the XbelReader in QXmlStream Bookmarks Example, which wraps a QXmlStreamReader. Read the implementation to learn more about how to use the QXmlStreamReader class.

Paired with QXmlStreamReader is the QXmlStreamWriter class, which provides an XML writer with a simple streaming API. QXmlStreamWriter operates on a QIODevice and has specialized functions for all XML tokens or events you want to write, such as writeDTD(), writeCharacters(), writeComment() and so on.

To write XML document with QXmlStreamWriter, you start a document with the writeStartDocument() function and end it with writeEndDocument(), which implicitly closes all remaining open tags. Element tags are opened with writeStartDocument() and followed by writeAttribute() or writeAttributes(), element content, and then writeEndDocument(). Also, writeEmptyElement() can be used to write empty elements.

Element content comprises characters, entity references or nested elements. Content can be written with writeCharacters(), a function that also takes care of escaping all forbidden characters and character sequences, writeEntityReference(), or subsequent calls to writeStartElement().

The XbelWriter class from QXmlStream Bookmarks Example wraps a QXmlStreamWriter. View the implementation to see how to use the QXmlStreamWriter class.