|  | Home · All Classes · Main Classes · Grouped Classes · Modules · Functions |

# QXmlStreamReader Class Reference
[QtXml module]

The QXmlStreamReader class provides a fast well-formed XML parser with a simple streaming API. More...

     #include <QXmlStreamReader>

Note: All the functions in this class are reentrant.

- List of all members, including inherited members

### Public Types

- enum Error { NoError, CustomError, UnexpectedElementError, XmlNotWellFormedError, PrematureEndOfDocumentError }
- enum TokenType { NoToken, Invalid, StartDocument, EndDocument, ..., ProcessingInstruction }

### Properties

- namespaceProcessing : bool

### Public Functions

- QXmlStreamReader ()
- QXmlStreamReader ( QIODevice * device )
- QXmlStreamReader ( const QByteArray & data )
- QXmlStreamReader ( const QString & data )
- QXmlStreamReader ( const char * data )
- ~QXmlStreamReader ()
- void addData ( const QByteArray & data )
- void addData ( const QString & data )
- void addData ( const char * data )
- bool atEnd () const
- QXmlStreamAttributes attributes () const
- qint64 characterOffset () const
- void clear ()
- qint64 columnNumber () const
- QIODevice * device () const
- QXmlStreamEntityDeclarations entityDeclarations () const
- Error error () const
- QString errorString () const
- bool isCDATA () const
- bool isCharacters () const
- bool isComment () const
- bool isDTD () const
- bool isEndDocument () const
- bool isEndElement () const
- bool isEntityReference () const
- bool isProcessingInstruction () const
- bool isStandaloneDocument () const
- bool isStartDocument () const
- bool isStartElement () const
- bool isWhitespace () const
- qint64 lineNumber () const
- QStringRef name () const
- QXmlStreamNamespaceDeclarations namespaceDeclarations () const
- bool namespaceProcessing () const
- QStringRef namespaceUri () const
- QXmlStreamNotationDeclarations notationDeclarations () const
- QStringRef processingInstructionData () const
- QStringRef processingInstructionTarget () const
- QStringRef qualifiedName () const
- void raiseError ( const QString & message = QString() )
- QString readElementText ()
- TokenType readNext ()
- void setDevice ( QIODevice * device )
- void setNamespaceProcessing ( bool )
- QStringRef text () const
- QString tokenString () const
- TokenType tokenType () const

## Detailed Description

The QXmlStreamReader class provides a fast well-formed XML parser with a simple streaming API.

QXmlStreamReader is a faster and more convenient replacement for Qt's own SAX parser (see QXmlSimpleReader), and in some cases also for applications that would previously use a DOM tree (see QDomDocument). QXmlStreamReader reads data either from a QIODevice (see setDevice()), or from a raw QByteArray (see addData()). With QXmlStreamWriter, Qt provides a related class for writing XML.

The basic concept of a stream reader is to report an XML document as a stream of tokens, similar to SAX. The main difference between QXmlStreamReader and SAX is how these XML tokens are reported. With SAX, the application must provide handlers that receive so-called XML events from the parser at the parser's convenience. With QXmlStreamReader, the application code itself drives the loop and pulls tokens from the reader one after another as it needs them. This is done by calling readNext(), which makes the reader read from the input stream until it has completed a new token, and then returns its tokenType(). A set of convenient functions like isStartElement() or text() then allows to examine this token, and to obtain information about what has been read. The big advantage of the pulling approach is the possibility to build recursive descent parsers, meaning you can split your XML parsing code easily into different methods or classes. This makes it easy to keep track of the application's own state when parsing XML.

A typical loop with QXmlStreamReader looks like this:

     QXmlStreamReader xml;
     ...
     while (!xml.atEnd()) {
           xml.readNext();
           ... // do processing
     }
     if (xml.error()) {
           ... // do error handling
     }

QXmlStreamReader is a well-formed XML 1.0 parser that does not include external parsed entities. As long as no error occurs, the application code can thus be assured that the data provided by the stream reader satisfies the W3C's criteria for well-formed XML. For example, you can be certain that all tags are indeed nested and closed properly, that references to internal entities have been replaced with the correct replacement text, and that attributes have been normalized or added according to the internal subset of the DTD.

If an error does occur while parsing, atEnd() returns true and error() returns the kind of error that occured. The functions errorString(), lineNumber(), columnNumber(), and characterOffset() make it possible to generate a verbose human-understandable error or warning message. In order to simplify application code, QXmlStreamReader contains a raiseError() mechanism that makes it possible to raise custom errors that then trigger the same error handling code path.

The QXmlStream Bookmarks Example illustrates how to use the recursive descent technique with a subclassed stream reader to read an XML bookmark file (XBEL).

### Namespaces

QXmlStream understands and resolves XML namespaces. E.g. in case of a StartElement, namespaceUri() returns the namespace the element is in, and name() returns the element's local name. The combination of namespaceUri and name uniquely identifies an element. If a namespace prefix was not declared in the XML entities parsed by the reader, the namespaceUri is empty.

If you parse XML data that does not utilize namespaces according to the XML specification or doesn't use namespaces at all, you can use the element's qualifiedName() instead. A qualified name is the element's prefix followed by colon followed by the element's local name - exactly like the element appears in the raw XML data. Since the mapping namespaceUri to prefix is neither unique nor universal, qualifiedName() should be avoided for namespace-compliant XML data.

In order to parse standalone documents that do use undeclared namespace prefixes, you can turn off namespace processing completely with the namespaceProcessing property.

### Incremental parsing

QXmlStreamReader is an incremental parser. If you can't parse the entire input in one go (for example, it is huge, or is being delivered over a network connection), data can be fed to the parser in pieces. If the reader runs out of data before the document has been parsed completely, it reports a PrematureEndOfDocumentError. Once more data has arrived, either through the device or because it has been added with addData(), it recovers from that error and continues parsing on the next call to read().

For example, if you read data from the network using QHttp, you would connect its readyRead() signal to a custom slot. In this slot, you read all available data with readAll() and pass it to the XML stream reader using addData(). Then you call your custom parsing function that reads the XML events from the reader.

### Performance and memory consumption

QXmlStreamReader is memory-conservative by design, since it doesn't store the entire XML document tree in memory, but only the current token at the time it is reported. In addition, QXmlStreamReader avoids the many small string allocations that it normally takes to map an XML document to a convenient and Qt-ish API. It does this by reporting all string data as QStringRef rather than real QString objects. QStringRef is a thin wrapper around QString substrings that provides a subset of the QString API without the memory allocation and reference-counting overhead. Calling toString() on any of those objects returns an equivalent real QString object.

## Member Type Documentation

### enum QXmlStreamReader::Error

This enum specifies different error cases

Constant | Value | Description
--- | --- | ---
`QXmlStreamReader::NoError` | `0` | No error has occured.
`QXmlStreamReader::CustomError` | `1` | A custom error has been raised with raiseError()
`QXmlStreamReader::UnexpectedElementError` | `2` | An unexpected element was read in readElementText().
`QXmlStreamReader::XmlNotWellFormedError` | `4` | The parser internally raised an error due to the read XML not being well-formed.
`QXmlStreamReader::PrematureEndOfDocumentError` | `5` | The input stream ended before the document was parsed completely. This error can be recovered from.

### enum QXmlStreamReader::TokenType

This enum specifies the type of token the reader just read.

Constant | Value | Description
--- | --- | ---
`QXmlStreamReader::NoToken` | `0` | The reader has not yet read anything.
`QXmlStreamReader::Invalid` | `1` | An error has occured, reported in error() and errorString().
`QXmlStreamReader::StartDocument` | `2` | The reader reports the start of the document. If the document is declared standalone, isStandaloneDocument() returns true; otherwise it returns false.
`QXmlStreamReader::EndDocument` | `3` | The reader reports the end of the document.
`QXmlStreamReader::StartElement` | `4` | The reader reports the start of an element with namespaceUri() and name(). Empty elements are also reported as StartElement, followed directly by EndElement. The convenience function readElementText() can be called to concatenate all content until the corresponding EndElement. Attributes are reported in attributes(), namespace declarations in namespaceDeclarations().
`QXmlStreamReader::EndElement` | `5` | The reader reports the end of an element with namespaceUri() and name().
`QXmlStreamReader::Characters` | `6` | The reader reports characters in text(). If the characters are all white-space, isWhitespace() returns true. If the characters stem from a CDATA section, isCDATA() returns true.
`QXmlStreamReader::Comment` | `7` | The reader reports a comment in text().
`QXmlStreamReader::DTD` | `8` | The reader reports a DTD in text(), notation declarations in notationDeclarations().
`QXmlStreamReader::EntityReference` | `9` | The reader reports an entity reference that could not be resolved. The name of the reference is reported in name(), the replacement text in text().
`QXmlStreamReader::ProcessingInstruction` | `10` | The reader reports a processing instruction in processingInstructionTarget() and processingInstructionData().

## Property Documentation

### namespaceProcessing : bool

the namespace-processing flag of the stream reader

This property controls whether or not the stream reader processes namespaces. If enabled, the reader processes namespaces, otherwise it does not.

By default, namespace-processing is disabled.

Access functions:

- bool namespaceProcessing () const
- void setNamespaceProcessing ( bool )

## Member Function Documentation

### QXmlStreamReader::QXmlStreamReader ()

Constructs a stream reader.

See also setDevice() and addData().

### QXmlStreamReader::QXmlStreamReader ( QIODevice * device )

Creates a new stream reader that reads from device.

See also setDevice() and clear().

### QXmlStreamReader::QXmlStreamReader ( const QByteArray & data )

Creates a new stream reader that reads from data.

See also addData(), clear(), and setDevice().

### QXmlStreamReader::QXmlStreamReader ( const QString & data )

Creates a new stream reader that reads from data.

See also addData(), clear(), and setDevice().

### QXmlStreamReader::QXmlStreamReader ( const char * data )

Creates a new stream reader that reads from data.

See also addData(), clear(), and setDevice().

### QXmlStreamReader::~QXmlStreamReader ()

Destructs the reader.

### void QXmlStreamReader::addData ( const QByteArray & data )

Adds more data for the reader to read.

This function does nothing if the reader has a device().

See also clear().

### void QXmlStreamReader::addData ( const QString & data )

This is an overloaded member function, provided for convenience.

Adds more data for the reader to read.

This function does nothing if the reader has a device().

See also clear().

### void QXmlStreamReader::addData ( const char * data )

This is an overloaded member function, provided for convenience.

Adds more data for the reader to read.

This function does nothing if the reader has a device().

See also clear().

### bool QXmlStreamReader::atEnd () const

Returns true if the reader has read until the end of the XML document, or an error has occured and reading has been aborted; otherwise returns false.

Has reading been aborted with a PrematureEndOfDocumentError because the device no longer delivered data, atEnd() will return true once more data has arrived.

See also device() and QIODevice::atEnd().

### QXmlStreamAttributes QXmlStreamReader::attributes () const

Returns the attributes of a StartElement.

### qint64 QXmlStreamReader::characterOffset () const

Returns the current character offset, starting with 0.

See also lineNumber() and columnNumber().

### void QXmlStreamReader::clear ()

Removes any device() or data from the reader, and resets its state to the initial state.

See also addData().

### qint64 QXmlStreamReader::columnNumber () const

Returns the current column number, starting with 0.

See also lineNumber() and characterOffset().

### QIODevice * QXmlStreamReader::device () const

Returns the current device associated with the QXmlStreamReader, or 0 if no device has been assigned.

See also setDevice().

### QXmlStreamEntityDeclarations QXmlStreamReader::entityDeclarations () const

If the state() is DTD, this function returns the DTD's unparsed (external) entity declarations. Otherwise an empty vector is returned.

The QXmlStreamEntityDeclarations class is defined to be a QVector of QXmlStreamEntityDeclaration.

### Error QXmlStreamReader::error () const

Returns the type of the current error, or NoError if no error occured.

See also errorString() and raiseError().

### QString QXmlStreamReader::errorString () const

Returns the error message that was set with raiseError().

See also error(), lineNumber(), columnNumber(), and characterOffset().

### bool QXmlStreamReader::isCDATA () const

Returns true if the reader reports characters that stem from a CDATA section; otherwise returns false.

See also isCharacters() and text().

### bool QXmlStreamReader::isCharacters () const

Returns true if tokenType() equals Characters; otherwise returns false.

See also isWhitespace() and isCDATA().

### bool QXmlStreamReader::isComment () const

Returns true if tokenType() equals Comment; otherwise returns false.

### bool QXmlStreamReader::isDTD () const

Returns true if tokenType() equals DTD; otherwise returns false.

### bool QXmlStreamReader::isEndDocument () const

Returns true if tokenType() equals EndDocument; otherwise returns false.

### bool QXmlStreamReader::isEndElement () const

Returns true if tokenType() equals EndElement; otherwise returns false.

### bool QXmlStreamReader::isEntityReference () const

Returns true if tokenType() equals EntityReference; otherwise returns false.

### bool QXmlStreamReader::isProcessingInstruction () const

Returns true if tokenType() equals ProcessingInstruction; otherwise returns false.

### bool QXmlStreamReader::isStandaloneDocument () const

Returns true if this document has been declared standalone in the XML declaration; otherwise returns false.

If no XML declaration has been parsed, this function returns false.

### bool QXmlStreamReader::isStartDocument () const

Returns true if tokenType() equals StartDocument; otherwise returns false.

### bool QXmlStreamReader::isStartElement () const

Returns true if tokenType() equals StartElement; otherwise returns false.

### bool QXmlStreamReader::isWhitespace () const

Returns true if the reader reports characters that only consist of white-space; otherwise returns false.

See also isCharacters() and text().

### qint64 QXmlStreamReader::lineNumber () const

Returns the current line number, starting with 1.

See also columnNumber() and characterOffset().

### QStringRef QXmlStreamReader::name () const

Returns the local name of a StartElement, EndElement, or an EntityReference.

See also namespaceUri() and qualifiedName().

### QXmlStreamNamespaceDeclarations QXmlStreamReader::namespaceDeclarations () const

If the state() is StartElement, this function returns the element's namespace declarations. Otherwise an empty vector is returned.

The QXmlStreamNamespaceDeclaration class is defined to be a QVector of QXmlStreamNamespaceDeclaration.

### QStringRef QXmlStreamReader::namespaceUri () const

Returns the namespaceUri of a StartElement or EndElement.

See also name() and qualifiedName().

### QXmlStreamNotationDeclarations QXmlStreamReader::notationDeclarations () const

If the state() is DTD, this function returns the DTD's notation declarations. Otherwise an empty vector is returned.

The QXmlStreamNotationDeclarations class is defined to be a QVector of QXmlStreamNotationDeclaration.

### QStringRef QXmlStreamReader::processingInstructionData () const

Returns the data of a ProcessingInstruction.

### QStringRef QXmlStreamReader::processingInstructionTarget () const

Returns the target of a ProcessingInstruction.

### QStringRef QXmlStreamReader::qualifiedName () const

Returns the qualified name of a StartElement or EndElement;

A qualified name is the raw name of an element in the XML data. It consists of the namespace prefix, followed by colon, followed by the element's local name. Since the namespace prefix is not unique (the same prefix can point to different namespaces and different prefixes can point to the same namespace), you shouldn't use qualifiedName(), but the resolved namespaceUri() and the attribute's local name().

See also name() and namespaceUri().

### void QXmlStreamReader::raiseError ( const QString & message = QString() )

Raises a custom error with an optional error message.

See also error() and errorString().

### QString QXmlStreamReader::readElementText ()

Convenience function to be called in case a StartElement was read. Reads until the corresponding EndElement and returns all text in-between. In case of no error, the token after having called this function is EndElement.

The function concatenates text() when it reads either Characters or EntityReference tokens, but skips ProcessingInstruction and Comment. In case anything else is read before reaching EndElement, the function returns what it read so far and raises an UnexpectedElementError. If the current token is not StartElement, an empty string is returned.

### TokenType QXmlStreamReader::readNext ()

Reads the next token and returns its type.

If an error() has been reported, reading is no longer possible. In this case, atEnd() always returns true, and this function will do nothing but return Invalid.

The one exception to this rule are errors of type PrematureEndOfDocumentError. Subsequent calls to atEnd() and readNext() will resume this error type and try to read from the device again. This iterative parsing approach makes sense if you can't or don't want to read the entire data in one go, for example, if it is huge, or it is being delivered over a network connection

See also tokenType() and tokenString().

### void QXmlStreamReader::setDevice ( QIODevice * device )

Sets the current device to device. Setting the device resets the stream to its initial state.

See also device() and clear().

### QStringRef QXmlStreamReader::text () const

Returns the text of Characters, Comment, DTD, or EntityReference.

### QString QXmlStreamReader::tokenString () const

Returns the reader's current token as string.

See also tokenType().

### TokenType QXmlStreamReader::tokenType () const

Returns the type of the current token.

The current token can also be queried with the convenience functions isStartDocument(), isEndDocument(), isStartElement(), isEndElement(), isCharacters(), isComment(), isDTD(), isEntityReference(), and isProcessingInstruction()

See also tokenString().