![]() |
Главная · Все классы · Основные классы · Классы по группам · Модули · Функции | ![]() |
Класс 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.
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.
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.
Это перечисление определяет различные случаи ошибок
Константа | Значение | Описание |
---|---|---|
QXmlStreamReader::NoError | 0 | Нет ошибок. |
QXmlStreamReader::CustomError | 2 | Собственная ошибка была инициирована с помощью raiseError() |
QXmlStreamReader::NotWellFormedError | 3 | Анализатор вызвал внутреннюю ошибку, так как XML содержит синтаксические ошибки. |
QXmlStreamReader::PrematureEndOfDocumentError | 4 | Входящий поток оборвался до того, как анализируемый документ был полностью прочитан. Ошибка может быть исправлена |
QXmlStreamReader::UnexpectedElementError | 1 | Анализатор встретил неожиданный элемент. |
Это перечисление определяет типы маркеров, которые только что были прочитаны.
Константа | Значение | Описание |
---|---|---|
QXmlStreamReader::NoToken | 0 | Пока не прочитано ни одно маркера. |
QXmlStreamReader::Invalid | 1 | Произошла ошибка, подробнее в error() и 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 | Читатель сообщает о конце документа. |
QXmlStreamReader::StartElement | 4 | Читатель сообщает о начале элемента с URI пространства имён namespaceUri() и именем name(). О пустых элементах также сообщается в виде StartElement с последующим сразу EndElement. Удобная функция readElementText() может быть вызвана для объединения всего содержимого до соответствующего EndElement. Об атрибутах сообщается в attributes(), пространства имён декларируются в namespaceDeclarations(). |
QXmlStreamReader::EndElement | 5 | Читатель сообщает о конце элемента с URI пространства имён namespaceUri() и именем name(). |
QXmlStreamReader::Characters | 6 | Читатель сообщает о символах в text(). Если полученый текст состоит из символов пустого пространства, isWhitespace() вернёт true. Если полученный текст из области CDATA, isCDATA() вернёт true. |
QXmlStreamReader::Comment | 7 | Читатель сообщает о комментарии в text(). |
QXmlStreamReader::DTD | 8 | The reader reports a DTD in text(), notation declarations in notationDeclarations(). |
QXmlStreamReader::EntityReference | 9 | Читатель сообщает о ссылке на сущность, которая не может быть разрешена. Имя ссылки на сущность сообщается в name(), заменяемый текст - вtext(). |
QXmlStreamReader::ProcessingInstruction | 10 | Читатель сообщает о инструкции обработки в processingInstructionTarget() и processingInstructionData(). |
флаг обработки пространств имён потоком чтения
Это свойство определяет, обрабатывает или нет поток пространства имён. Если оно включено, читатель будет обрабатывать пространства имён, в противном случае - нет.
По-умолчанию обработка пространств имён включена.
Функции доступа:
Создаёт поток чтения.
Смотрите также setDevice() и addData().
Создаёт поток чтения, который рабтает с устройством device.
Смотрите также setDevice() и clear().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Уничтожает объект читателя.
Добавляет больше данных data в поток для чтения.
Эта функция ничего не делает, если читатель работает с устройством device().
Смотрите также clear().
Это перегруженная функция, предоставленная для удобства.
Добавляет больше данных data в поток для чтения.
Эта функция ничего не делает, если читатель работает с устройством device().
Смотрите также clear().
Это перегруженная функция, предоставленная для удобства.
Добавляет больше данных data в поток для чтения.
Эта функция ничего не делает, если читатель работает с устройством device().
Смотрите также clear().
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().
Returns the attributes of a StartElement.
Returns the current character offset, starting with 0.
See also lineNumber() and columnNumber().
Removes any device() or data from the reader, and resets its state to the initial state.
See also addData().
Returns the current column number, starting with 0.
See also lineNumber() and characterOffset().
Returns the current device associated with the QXmlStreamReader, or 0 if no device has been assigned.
Смотрите также setDevice().
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.
Returns the type of the current error, or NoError if no error occurred.
See also errorString() and raiseError().
Returns the error message that was set with raiseError().
See also error(), lineNumber(), columnNumber(), and characterOffset().
Returns true if an error has occurred, otherwise false.
See also errorString() and error().
Returns true if the reader reports characters that stem from a CDATA section; otherwise returns false.
Смотрите также isCharacters() и text().
Возвращает true, если tokenType() равен Characters; в противном случае возвращает false.
Смотрите также isWhitespace() и isCDATA().
Возвращает true, если tokenType() равен Comment; в противном случае возвращает false.
Возвращает true, если tokenType() равен DTD; в противном случае возвращает false.
Возвращает true, если tokenType() равен EndDocument; в противном случае возвращает false.
Возвращает true, если tokenType() равен EndElement; в противном случае возвращает false.
Возвращает true, если tokenType() равен EntityReference; в противном случае возвращает false.
Возвращает true, если tokenType() равен ProcessingInstruction; в противном случае возвращает false.
Возвращает true, если текущий документ был объявлен автономным в декларации XML; в противном случае возвращает false.
Если не было проанализировано XML декларации, эта функция вернёт false.
Возвращает true, если tokenType() равен StartDocument; в противном случае возвращает false.
Возвращает true, если tokenType() равен StartElement; в противном случае возвращает false.
Возвращает true, если отчёт читателя содержит только символы пустого пространства; в противном случае возвращает false.
Смотрите также isCharacters() и text().
Возвращает текущий номер строки, начиная с 1.
Смотрите также columnNumber() и characterOffset().
Returns the local name of a StartElement, EndElement, or an EntityReference.
See also namespaceUri() and qualifiedName().
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.
Returns the namespaceUri of a StartElement or EndElement.
See also name() and qualifiedName().
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.
Returns the data of a ProcessingInstruction.
Returns the target of a ProcessingInstruction.
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().
Raises a custom error with an optional error message.
Смотрите также error() и errorString().
Удобная функция, вызываемая, если прочитан 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, возвращается пустая строка.
Читает следующий символ и возвращает его тип.
Если произошла ошибка error(), чтение больше невозможно. В этом случае atEnd() всегда возвращает true, а текущая функция ничего не делает и возвращает Invalid.
Для ошибок такого типа есть PrematureEndOfDocumentError. Последующий вызов atEnd() и readNext() возобновит работу после ошибки и попробует прочитать с устройства снова. Этот метод итеративного анализа имеет смысл, если вы не хотите прочитать данные за один проход, например, если их много или они приходят по сети.
Смотрите также tokenType() и tokenString().
Устанавливает текущее устройство в device. Переданное устройство переключает поток в начальное состояние.
Смотрите также device() и clear().
Возвращает текст Characters, Comment, DTD или EntityReference.
Возвращает текущий маркер в виде строки.
Смотрите также tokenType().
Возвращает тип текущего маркера.
Тип текущего маркера может быть запрошен с помощью удобных фукнций isStartDocument(), isEndDocument(), isStartElement(), isEndElement(), isCharacters(), isComment(), isDTD(), isEntityReference() и isProcessingInstruction()
Смотрите также tokenString().
Copyright © 2008 Trolltech | Торговые марки | Qt 4.3.5 |