Описание класса QXmlStreamReader
|
| enum | Error { NoError, CustomError, NotWellFormedError, PrematureEndOfDocumentError, UnexpectedElementError } |
| enum | ReadElementTextBehaviour { ErrorOnUnexpectedElement, IncludeChildElements, SkipChildElements } |
| enum | TokenType { NoToken, Invalid, StartDocument, EndDocument, ..., ProcessingInstruction } |
| 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 ) |
| void | addExtraNamespaceDeclaration ( const QXmlStreamNamespaceDeclaration & extraNamespaceDeclaration ) |
| void | addExtraNamespaceDeclarations ( const QXmlStreamNamespaceDeclarations & extraNamespaceDeclarations ) |
| bool | atEnd () const |
| QXmlStreamAttributes | attributes () const |
| qint64 | characterOffset () const |
| void | clear () |
| qint64 | columnNumber () const |
| QIODevice * | device () const |
| QStringRef | documentEncoding () const |
| QStringRef | documentVersion () const |
| QStringRef | dtdName () const |
| QStringRef | dtdPublicId () const |
| QStringRef | dtdSystemId () const |
| QXmlStreamEntityDeclarations | entityDeclarations () const |
| QXmlStreamEntityResolver * | entityResolver () const |
| Error | error () const |
| QString | errorString () const |
| bool | hasError () 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 | prefix () const |
| QStringRef | processingInstructionData () const |
| QStringRef | processingInstructionTarget () const |
| QStringRef | qualifiedName () const |
| void | raiseError ( const QString & message = QString() ) |
| QString | readElementText ( ReadElementTextBehaviour behaviour ) |
| QString | readElementText () |
| TokenType | readNext () |
| bool | readNextStartElement () |
| void | setDevice ( QIODevice * device ) |
| void | setEntityResolver ( QXmlStreamEntityResolver * resolver ) |
| void | setNamespaceProcessing ( bool ) |
| void | skipCurrentElement () |
| QStringRef | text () const |
| QString | tokenString () const |
| TokenType | tokenType () const |
The QXmlStreamReader class provides a fast parser for reading well-formed XML via a simple streaming API.
QXmlStreamReader is a faster and more convenient replacement for Qt's own SAX parser (see QXmlSimpleReader). In some cases it might also be a faster and more convenient alternative for use in applications that would otherwise use a DOM tree (see QDomDocument). QXmlStreamReader считывает данные с QIODevice (смотрите setDevice()) или с необработанного QByteArray (смотрите addData()).
Qt provides QXmlStreamWriter for writing XML.
Базовая концепция потокового чтения состоит в представлении XML документа в виде потока маркеров (tokens), по аналогии с SAX. Главное отличие QXmlStreamReader от SAX состоит в том, как эти XML маркеры представляются. With SAX, the application must provide handlers (callback functions) 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(), where the reader reads from the input stream until it completes the next token, at which point it returns the tokenType(). A set of convenient functions including isStartElement() and text() can then be used to examine the token to obtain information about what has been read. The big advantage of this pulling approach is the possibility to build recursive descent parsers with it, meaning you can split your XML parsing code easily into different methods or classes. Это позволяет легко сохранять состояние приложения при анализе 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 occurs while parsing, atEnd() and hasError() return true, and error() returns the error that occurred. The functions errorString(), lineNumber(), columnNumber(), and characterOffset() are for constructing an appropriate error or warning message. To simplify application code, QXmlStreamReader contains a raiseError() mechanism that lets you raise custom errors that trigger the same error handling described.
The QXmlStream Bookmarks Example illustrates how to use the recursive descent technique to read an XML bookmark file (XBEL) with a stream reader.
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. It can handle the case where the document can't be parsed all at once because it arrives in chunks (e.g. from multiple files, or over a network connection). When the reader runs out of data before the complete document has been parsed, it reports a PrematureEndOfDocumentError. When more data arrives, either because of a call to addData() or because more data is available through the network device(), the reader recovers from the PrematureEndOfDocumentError error and continues parsing the new data with the next call to readNext().
For example, if your application reads data from the network using a network access manager, you would issue a network request to the manager and receive a network reply in return. Since a QNetworkReply is a QIODevice, you connect its readyRead() signal to a custom slot, e.g. slotReadyRead() in the code snippet shown in the discussion for QNetworkAccessManager. 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 | The input stream ended before a well-formed XML document was parsed. Recovery from this error is possible if more XML arrives in the stream, either by calling addData() or by waiting for it to arrive on the device(). |
| QXmlStreamReader::UnexpectedElementError | 1 | Анализатор встретил неожиданный элемент. |
This enum specifies the different behaviours of readElementText().
| Константа | Значение | Описание |
|---|---|---|
| QXmlStreamReader::ErrorOnUnexpectedElement | 0 | Raise an UnexpectedElementError and return what was read so far when a child element is encountered. |
| QXmlStreamReader::IncludeChildElements | 1 | Recursively include the text from child elements. |
| QXmlStreamReader::SkipChildElements | 2 | Skip child elements. |
Данное перечисление было введено в Qt 4.6.
Это перечисление определяет типы маркеров, которые только что были прочитаны.
| Константа | Значение | Описание |
|---|---|---|
| QXmlStreamReader::NoToken | 0 | Пока не прочитано ни одно маркера. |
| QXmlStreamReader::Invalid | 1 | Произошла ошибка, подробнее в error() и errorString(). |
| QXmlStreamReader::StartDocument | 2 | Читатель сообщает о номере версии XML в documentVersion() и о кодировке XML документа в documentEncoding(). Если документ определён как самостоятельный, isStandaloneDocument() вернёт true; в противном случае возвращается 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 | Читатель сообщает о DTD в text(), о нотации декларации в notationDeclarations() о сущности декларации в entityDeclarations(). Детали декларации DTD доступны в dtdName(), dtdPublicId() и dtdSystemId(). |
| QXmlStreamReader::EntityReference | 9 | Читатель сообщает о ссылке на сущность, которая не может быть разрешена. Имя ссылки на сущность сообщается в name(), заменяемый текст - вtext(). |
| QXmlStreamReader::ProcessingInstruction | 10 | Читатель сообщает о инструкции обработки в processingInstructionTarget() и processingInstructionData(). |
флаг обработки пространств имён потоком чтения
Это свойство определяет, обрабатывает или нет поток пространства имён. Если оно включено, читатель будет обрабатывать пространства имён, в противном случае - нет.
По умолчанию обработка пространств имён включена.
Функции доступа:
| bool | namespaceProcessing () const |
| void | setNamespaceProcessing ( bool ) |
Создаёт поток чтения.
Смотрите также setDevice() и addData().
Создаёт поток чтения, который рабтает с устройством device.
Смотрите также setDevice() и clear().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Создаёт поток чтения, который читает с data.
Смотрите также addData(), clear() и setDevice().
Уничтожает объект читателя.
Добавляет больше данных data в поток для чтения. This function does nothing if the reader has a device().
See also readNext() and clear().
Добавляет больше данных data в поток для чтения. This function does nothing if the reader has a device().
See also readNext() and clear().
Добавляет больше данных data в поток для чтения. This function does nothing if the reader has a device().
See also readNext() and clear().
Добавляет extraNamespaceDeclaration. Декларация будет действительной для детей текущего элемента или - при вызове этой функции до чтения всех элементов - для всего XML документа.
Эта функция была введена в Qt 4.4.
Смотрите также namespaceDeclarations(), addExtraNamespaceDeclarations() и setNamespaceProcessing().
Добавляет вектор деклараций, определённых в extraNamespaceDeclarations.
Эта функция была введена в Qt 4.4.
Смотрите также namespaceDeclarations() и addExtraNamespaceDeclaration().
Returns true if the reader has read until the end of the XML document, or if an error() has occurred and reading has been aborted. Otherwise, it returns false.
When atEnd() and hasError() return true and error() returns PrematureEndOfDocumentError, it means the XML has been well-formed so far, but a complete XML document has not been parsed. The next chunk of XML can be added with addData(), if the XML is being read from a QByteArray, or by waiting for more data to arrive if the XML is being read from a QIODevice. Either way, atEnd() will return false once more adata is available.
See also hasError(), error(), 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 internal 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 StartDocument, this function returns the encoding string as specified in the XML declaration. В противном случае возвращается пустая строка.
Эта функция была введена в Qt 4.4.
If the state() is StartDocument, this function returns the version string as specified in the XML declaration. В противном случае возвращается пустая строка.
Эта функция была введена в Qt 4.4.
If the state() is DTD, this function returns the DTD's name. В противном случае возвращается пустая строка.
Эта функция была введена в Qt 4.4.
If the state() is DTD, this function returns the DTD's public identifier. В противном случае возвращается пустая строка.
Эта функция была введена в Qt 4.4.
If the state() is DTD, this function returns the DTD's system identifier. В противном случае возвращается пустая строка.
Эта функция была введена в Qt 4.4.
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 entity resolver, or 0 if there is no entity resolver.
Эта функция была введена в Qt 4.4.
See also setEntityResolver().
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.
See also addExtraNamespaceDeclaration() and addExtraNamespaceDeclarations().
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 prefix of a StartElement or EndElement.
Эта функция была введена в Qt 4.4.
See also name() and qualifiedName().
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(), prefix(), and namespaceUri().
Raises a custom error with an optional error message.
Смотрите также error() и errorString().
Вспомогательная функция, вызываемая, если прочитан StartElement. Читает пока не встретится EndElement и возвращает текст между элементами. In case of no error, the current token (see tokenType()) after having called this function is EndElement.
The function concatenates text() when it reads either Characters or EntityReference tokens, but skips ProcessingInstruction and Comment. If the current token is not StartElement, an empty string is returned.
The behaviour defines what happens in case anything else is read before reaching EndElement. The function can include the text from child elements (useful for example for HTML), ignore child elements, or raise an UnexpectedElementError and return what was read so far.
Эта функция была введена в Qt 4.6.
This function overloads readElementText().
Calling this function is equivalent to calling readElementText(ErrorOnUnexpectedElement).
Читает следующий символ и возвращает его тип.
With one exception, once an error() is reported by readNext(), further reading of the XML stream is not possible. Then atEnd() returns true, hasError() returns true, and this function returns QXmlStreamReader::Invalid.
The exception is when error() returns PrematureEndOfDocumentError. This error is reported when the end of an otherwise well-formed chunk of XML is reached, but the chunk doesn't represent a complete XML document. In that case, parsing can be resumed by calling addData() to add the next chunk of XML, when the stream is being read from a QByteArray, or by waiting for more data to arrive when the stream is being read from a device().
Смотрите также tokenType() и tokenString().
Reads until the next start element within the current element. Returns true when a start element was reached. When the end element was reached, or when an error occurred, false is returned.
The current element is the element matching the most recently parsed start element of which a matching end element has not yet been reached. When the parser has reached the end element, the current element becomes the parent element.
This is a convenience function for when you're only concerned with parsing XML elements. The QXmlStream Bookmarks Example makes extensive use of this function.
Эта функция была введена в Qt 4.6.
See also readNext().
Устанавливает текущее устройство в device. Переданное устройство переключает поток в начальное состояние.
Смотрите также device() и clear().
Устанавливает распознватель resolver в качестве распознавателя сущностей entityResolver().
Поток чтения не владеет этим распознавателем. Обязаность вызвавшего фунцию - убедиться, что распознаватель будет валиден в течении жизни объекта потока чтения или пока новый распознаватель или 0 не будут установлены.
Эта функция была введена в Qt 4.4.
Смотрите также entityResolver().
Reads until the end of the current element, skipping any child nodes. This function is useful for skipping unknown elements.
The current element is the element matching the most recently parsed start element of which a matching end element has not yet been reached. When the parser has reached the end element, the current element becomes the parent element.
Эта функция была введена в Qt 4.6.
Возвращает текст Characters, Comment, DTD или EntityReference.
Возвращает текущий маркер в виде строки.
Смотрите также tokenType().
Возвращает тип текущего маркера.
The current token can also be queried with the convenience functions isStartDocument(), isEndDocument(), isStartElement(), isEndElement(), isCharacters(), isComment(), isDTD(), isEntityReference(), and isProcessingInstruction().
Смотрите также tokenString().
| Авторские права © 2010 Nokia Corporation и/или её дочерние компании | Торговые марки | Qt 4.6.4 |
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |