Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Описание класса QXmlStreamReader
[модуль QtXml]

Класс QXmlStreamReader представляет собой быстрый синтаксически корректный XML анализатор с простым потоковым API. Далее...

 #include <QXmlStreamReader>

Замечание: Все функции в этом классе реентерабельны.

Класс был добавлен в Qt 4.3.

Открытые типы

Свойства

Открытые функции


Подробное описание

Класс QXmlStreamReader представляет собой быстрый синтаксически корректный XML анализатор с простым потоковым API.

QXmlStreamReader является быстрым и более удобным для замены в Qt анализатора SAX (смотрите QXmlSimpleReader), а в некоторых случаях он даже более предпочтителен, чем использование DOM дерева (смотрите QDomDocument). QXmlStreamReader считывает данные с QIODevice (смотрите setDevice()) или с необработанного QByteArray (смотрите addData()). Вместе с QXmlStreamWriter Qt обеспечивает связанный класс для записи XML.

Базовая концепция потокового чтения состоит в представлении XML документа в виде потока маркеров (tokens), по аналогии с SAX. Главное отличие QXmlStreamReader от SAX состоит в том, как эти XML маркеры представляются. При использовании SAX приложение должно создать обработчики, которые получают так называемые XML события от анализатора так, как это ему удобно. С QXmlStreamReader код приложения сам управляет циклами и берёт маркеры из читателя один за другим, когда это нужно. Это реализовано с помощью вызова readNext(), что приводит к чтению из входного потока, пока не сформируется маркер, после чего возвращается его tokenType(). Набор удобных функций, например isStartElement() или text(), позволят изучить полученный маркер, а также получить информацию о том, что было прочитано. Большое преимущество такого типа чтения в возможности создания рекурсивных спускаемых анализаторов, это означает, что вы можете разделить ваш код анализа XML на различные методы или классы. Это позволяет легко сохранять состояние приложения при анализе XML.

Типичный цикл с QXmlStreamReader выглядит так:

 QXmlStreamReader xml;
 ...
 while (!xml.atEnd()) {
       xml.readNext();
       ... // обрабатываем
 }
 if (xml.hasError()) {
       ... // обработка ошибок
 }

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 occurred. hasError() can also be used to check whether an error has occurred. 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).

Пространства имен

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. Вызов toString() у любого из этих объектов вернёт объект, эквивалентный реальному QString.


Описание типов

enum QXmlStreamReader::Error

Это перечисление определяет различные случаи ошибок

КонстантаЗначениеОписание
QXmlStreamReader::NoError0Нет ошибок.
QXmlStreamReader::CustomError2Собственная ошибка была инициирована с помощью raiseError()
QXmlStreamReader::NotWellFormedError3Анализатор вызвал внутреннюю ошибку, так как XML содержит синтаксические ошибки.
QXmlStreamReader::PrematureEndOfDocumentError4Входящий поток оборвался до того, как анализируемый документ был полностью прочитан. Ошибка может быть исправлена
QXmlStreamReader::UnexpectedElementError1Анализатор встретил неожиданный элемент.

enum QXmlStreamReader::TokenType

Это перечисление определяет типы маркеров, которые только что были прочитаны.

КонстантаЗначениеОписание
QXmlStreamReader::NoToken0Пока не прочитано ни одно маркера.
QXmlStreamReader::Invalid1Произошла ошибка, подробнее в error() и errorString().
QXmlStreamReader::StartDocument2The reader reports the start of the document. If the document is declared standalone, isStandaloneDocument() returns true; otherwise it returns false.
QXmlStreamReader::EndDocument3Читатель сообщает о конце документа.
QXmlStreamReader::StartElement4Читатель сообщает о начале элемента с URI пространства имён namespaceUri() и именем name(). О пустых элементах также сообщается в виде StartElement с последующим сразу EndElement. Удобная функция readElementText() может быть вызвана для объединения всего содержимого до соответствующего EndElement. Об атрибутах сообщается в attributes(), пространства имён декларируются в namespaceDeclarations().
QXmlStreamReader::EndElement5Читатель сообщает о конце элемента с URI пространства имён namespaceUri() и именем name().
QXmlStreamReader::Characters6Читатель сообщает о символах в text(). Если полученый текст состоит из символов пустого пространства, isWhitespace() вернёт true. Если полученный текст из области CDATA, isCDATA() вернёт true.
QXmlStreamReader::Comment7Читатель сообщает о комментарии в text().
QXmlStreamReader::DTD8The reader reports a DTD in text(), notation declarations in notationDeclarations().
QXmlStreamReader::EntityReference9Читатель сообщает о ссылке на сущность, которая не может быть разрешена. Имя ссылки на сущность сообщается в name(), заменяемый текст - вtext().
QXmlStreamReader::ProcessingInstruction10Читатель сообщает о инструкции обработки в processingInstructionTarget() и processingInstructionData().


Описание свойств

namespaceProcessing : bool

флаг обработки пространств имён потоком чтения

Это свойство определяет, обрабатывает или нет поток пространства имён. Если оно включено, читатель будет обрабатывать пространства имён, в противном случае - нет.

По-умолчанию обработка пространств имён включена.

Функции доступа:


Описание функций-членов

QXmlStreamReader::QXmlStreamReader ()

Создаёт поток чтения.

Смотрите также setDevice() и addData().

QXmlStreamReader::QXmlStreamReader ( QIODevice * device )

Создаёт поток чтения, который рабтает с устройством device.

Смотрите также setDevice() и clear().

QXmlStreamReader::QXmlStreamReader ( const QByteArray & data )

Создаёт поток чтения, который читает с data.

Смотрите также addData(), clear() и setDevice().

QXmlStreamReader::QXmlStreamReader ( const QString & data )

Создаёт поток чтения, который читает с data.

Смотрите также addData(), clear() и setDevice().

QXmlStreamReader::QXmlStreamReader ( const char * data )

Создаёт поток чтения, который читает с data.

Смотрите также addData(), clear() и setDevice().

QXmlStreamReader::~QXmlStreamReader ()

Уничтожает объект читателя.

void QXmlStreamReader::addData ( const QByteArray & data )

Добавляет больше данных data в поток для чтения.

Эта функция ничего не делает, если читатель работает с устройством device().

Смотрите также clear().

void QXmlStreamReader::addData ( const QString & data )

Это перегруженная функция, предоставленная для удобства.

Добавляет больше данных data в поток для чтения.

Эта функция ничего не делает, если читатель работает с устройством device().

Смотрите также clear().

void QXmlStreamReader::addData ( const char * data )

Это перегруженная функция, предоставленная для удобства.

Добавляет больше данных data в поток для чтения.

Эта функция ничего не делает, если читатель работает с устройством device().

Смотрите также clear().

bool QXmlStreamReader::atEnd () const

Returns true if the reader has read until the end of the XML document, or an error has occurred 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.

Смотрите также 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 occurred.

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::hasError () const

Returns true if an error has occurred, otherwise false.

See also errorString() and error().

bool QXmlStreamReader::isCDATA () const

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

Смотрите также isCharacters() и text().

bool QXmlStreamReader::isCharacters () const

Возвращает true, если tokenType() равен Characters; в противном случае возвращает false.

Смотрите также isWhitespace() и isCDATA().

bool QXmlStreamReader::isComment () const

Возвращает true, если tokenType() равен Comment; в противном случае возвращает false.

bool QXmlStreamReader::isDTD () const

Возвращает true, если tokenType() равен DTD; в противном случае возвращает false.

bool QXmlStreamReader::isEndDocument () const

Возвращает true, если tokenType() равен EndDocument; в противном случае возвращает false.

bool QXmlStreamReader::isEndElement () const

Возвращает true, если tokenType() равен EndElement; в противном случае возвращает false.

bool QXmlStreamReader::isEntityReference () const

Возвращает true, если tokenType() равен EntityReference; в противном случае возвращает false.

bool QXmlStreamReader::isProcessingInstruction () const

Возвращает true, если tokenType() равен ProcessingInstruction; в противном случае возвращает false.

bool QXmlStreamReader::isStandaloneDocument () const

Возвращает true, если текущий документ был объявлен автономным в декларации XML; в противном случае возвращает false.

Если не было проанализировано XML декларации, эта функция вернёт false.

bool QXmlStreamReader::isStartDocument () const

Возвращает true, если tokenType() равен StartDocument; в противном случае возвращает false.

bool QXmlStreamReader::isStartElement () const

Возвращает true, если tokenType() равен StartElement; в противном случае возвращает false.

bool QXmlStreamReader::isWhitespace () const

Возвращает true, если отчёт читателя содержит только символы пустого пространства; в противном случае возвращает false.

Смотрите также isCharacters() и text().

qint64 QXmlStreamReader::lineNumber () const

Возвращает текущий номер строки, начиная с 1.

Смотрите также columnNumber() и 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.

Смотрите также error() и errorString().

QString QXmlStreamReader::readElementText ()

Удобная функция, вызываемая, если прочитан StartElement. Читает пока не встретится EndElement и возвращает текст между элементами. Если не произошло ошибок, то маркер после её вызова равен 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. Если текущий символ не StartElement, возвращается пустая строка.

TokenType QXmlStreamReader::readNext ()

Читает следующий символ и возвращает его тип.

Если произошла ошибка error(), чтение больше невозможно. В этом случае atEnd() всегда возвращает true, а текущая функция ничего не делает и возвращает Invalid.

Для ошибок такого типа есть PrematureEndOfDocumentError. Последующий вызов atEnd() и readNext() возобновит работу после ошибки и попробует прочитать с устройства снова. Этот метод итеративного анализа имеет смысл, если вы не хотите прочитать данные за один проход, например, если их много или они приходят по сети.

Смотрите также tokenType() и tokenString().

void QXmlStreamReader::setDevice ( QIODevice * device )

Устанавливает текущее устройство в device. Переданное устройство переключает поток в начальное состояние.

Смотрите также device() и clear().

QStringRef QXmlStreamReader::text () const

Возвращает текст Characters, Comment, DTD или EntityReference.

QString QXmlStreamReader::tokenString () const

Возвращает текущий маркер в виде строки.

Смотрите также tokenType().

TokenType QXmlStreamReader::tokenType () const

Возвращает тип текущего маркера.

Тип текущего маркера может быть запрошен с помощью удобных фукнций isStartDocument(), isEndDocument(), isStartElement(), isEndElement(), isCharacters(), isComment(), isDTD(), isEntityReference() и isProcessingInstruction()

Смотрите также tokenString().


Copyright © 2008 Trolltech Торговые марки
Qt 4.3.5