QXmlStreamReader Class Reference

[ QtCore module]

The QXmlStreamReader class provides a fast parser for reading well-formed XML via a simple streaming API. 更多...

类型

方法


详细描述

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 reads data either from a QIODevice (见 setDevice ()),或从原生 QByteArray (见 addData ()).

Qt 提供 QXmlStreamWriter 为写入 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 (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 从 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 () 和 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. 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.hasError()) {
         ... // 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.

若发生错误当剖析时, atEnd () 和 hasError () 返回 true,和 error () returns the error that occurred. The functions errorString (), lineNumber (), columnNumber (),和 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.

QXmlStream Bookmarks 范例 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 () 代替。 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 特性。

Incremental parsing

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 从 PrematureEndOfDocumentError error and continues parsing the new data with the next call to readNext ().

For example, if your application reads data from the network 使用 network access manager , you would issue a network request to the manager and receive a network reply in return. Since a QNetworkReply 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.

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 对象。 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 对象。


类型文档编制

QXmlStreamReader.Error

此枚举指定不同错误情况

常量 描述
QXmlStreamReader.NoError 0 没有发生错误。
QXmlStreamReader.CustomError 2 引发自定义错误采有 raiseError ()
QXmlStreamReader.NotWellFormedError 3 The parser internally raised an error due to the read XML not being well-formed.
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 The parser encountered an element that was different to those it expected.

QXmlStreamReader.ReadElementTextBehaviour

此枚举指定不同行为在 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 元素。
QXmlStreamReader.SkipChildElements 2 跳过子级元素。

该枚举在 Qt 4.6 引入或被修改。

QXmlStreamReader.TokenType

此枚举指定读取器刚刚读取的令牌类型。

常量 描述
QXmlStreamReader.NoToken 0 读取器尚未读取任何内容。
QXmlStreamReader.Invalid 1 发生错误,报告在 error () 和 errorString ().
QXmlStreamReader.StartDocument 2 The reader reports the XML version number in documentVersion (),和 the encoding as specified in the XML document in documentEncoding ()。若 the document is declared standalone, isStandaloneDocument () returns true; otherwise it returns false.
QXmlStreamReader.EndDocument 3 The reader reports the end of the 文档。
QXmlStreamReader.StartElement 4 The reader reports the start of an element with namespaceUri () 和 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 () 和 name ().
QXmlStreamReader.Characters 6 The reader reports characters in text (). If the characters are all white-space, isWhitespace () 返回 true. If the characters stem from a CDATA section, isCDATA () returns true.
QXmlStreamReader.Comment 7 读取器报告注释按 text ().
QXmlStreamReader.DTD 8 The reader reports a DTD in text (), notation declarations in notationDeclarations (), and entity declarations in entityDeclarations (). Details of the DTD declaration are reported in in dtdName (), dtdPublicId (),和 dtdSystemId ().
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 ().

方法文档编制

QXmlStreamReader.__init__ ( self )

构造流读取器。

另请参阅 setDevice () 和 addData ().

QXmlStreamReader.__init__ ( self , QIODevice   device )

创建的新流读取器读取自 device .

另请参阅 setDevice () 和 clear ().

QXmlStreamReader.__init__ ( self , QByteArray   data )

创建的新流读取器读取自 data .

另请参阅 addData (), clear (),和 setDevice ().

QXmlStreamReader.__init__ ( self , QString  data )

创建的新流读取器读取自 data .

另请参阅 addData (), clear (),和 setDevice ().

QXmlStreamReader.addData ( self , QByteArray   data )

添加更多 data for the reader to read. This function does nothing if the reader has a device ().

另请参阅 readNext () 和 clear ().

QXmlStreamReader.addData ( self , QString  data )

添加更多 data for the reader to read. This function does nothing if the reader has a device ().

另请参阅 readNext () 和 clear ().

QXmlStreamReader.addExtraNamespaceDeclaration ( self , QXmlStreamNamespaceDeclaration   extraNamespaceDeclaraction )

添加 extraNamespaceDeclaration . The declaration will be valid for children of the current element, or - should the function be called before any elements are read - for the entire XML document.

该函数在 Qt 4.4 引入。

另请参阅 namespaceDeclarations (), addExtraNamespaceDeclarations (), and setNamespaceProcessing ().

QXmlStreamReader.addExtraNamespaceDeclarations ( self , list-of-QXmlStreamNamespaceDeclaration  extraNamespaceDeclaractions )

Adds a vector of declarations specified by extraNamespaceDeclarations .

该函数在 Qt 4.4 引入。

另请参阅 namespaceDeclarations () and addExtraNamespaceDeclaration ().

bool QXmlStreamReader.atEnd ( self )

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.

当 atEnd() 和 hasError () 返回 true 且 error () 返回 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 data is available.

另请参阅 hasError (), error (), device (),和 QIODevice.atEnd ().

QXmlStreamAttributes QXmlStreamReader.attributes ( self )

返回属性为 StartElement .

int QXmlStreamReader.characterOffset ( self )

返回当前字符偏移,从 0 开始。

另请参阅 lineNumber () 和 columnNumber ().

QXmlStreamReader.clear ( self )

移除任何 device () or data from the reader and resets its internal state to the initial state.

另请参阅 addData ().

int QXmlStreamReader.columnNumber ( self )

返回当前列号,从 0 开始。

另请参阅 lineNumber () 和 characterOffset ().

QIODevice QXmlStreamReader.device ( self )

返回被当前设备关联的 QXmlStreamReader , or 0 if no device has been assigned.

另请参阅 setDevice ().

QStringRef QXmlStreamReader.documentEncoding ( self )

If the state() is StartDocument , this function returns the encoding string as specified in the XML declaration. Otherwise an empty string is returned.

该函数在 Qt 4.4 引入。

QStringRef QXmlStreamReader.documentVersion ( self )

If the state() is StartDocument , this function returns the version string as specified in the XML declaration. Otherwise an empty string is returned.

该函数在 Qt 4.4 引入。

QStringRef QXmlStreamReader.dtdName ( self )

If the state() is DTD , this function returns the DTD's name. Otherwise an empty string is returned.

该函数在 Qt 4.4 引入。

QStringRef QXmlStreamReader.dtdPublicId ( self )

If the state() is DTD , this function returns the DTD's public identifier. Otherwise an empty string is returned.

该函数在 Qt 4.4 引入。

QStringRef QXmlStreamReader.dtdSystemId ( self )

If the state() is DTD , this function returns the DTD's system identifier. Otherwise an empty string is returned.

该函数在 Qt 4.4 引入。

list-of-QXmlStreamEntityDeclaration QXmlStreamReader.entityDeclarations ( self )

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

QXmlStreamEntityDeclarations class is defined to be a QVector of QXmlStreamEntityDeclaration .

QXmlStreamEntityResolver QXmlStreamReader.entityResolver ( self )

Returns the entity resolver, or 0 if there is no entity resolver.

该函数在 Qt 4.4 引入。

另请参阅 setEntityResolver ().

Error QXmlStreamReader.error ( self )

返回当前错误的类型,或 NoError if no error occurred.

另请参阅 errorString () 和 raiseError ().

QString QXmlStreamReader.errorString ( self )

返回错误消息,设置采用 raiseError ().

另请参阅 error (), lineNumber (), columnNumber (),和 characterOffset ().

bool QXmlStreamReader.hasError ( self )

返回 true 若有发生错误,否则 false .

另请参阅 errorString () 和 error ().

bool QXmlStreamReader.isCDATA ( self )

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

另请参阅 isCharacters () 和 text ().

bool QXmlStreamReader.isCharacters ( self )

返回 true 若 tokenType () 等于 Characters ;否则 returns false.

另请参阅 isWhitespace () 和 isCDATA ().

bool QXmlStreamReader.isComment ( self )

返回 true 若 tokenType () 等于 Comment ;否则 returns false.

bool QXmlStreamReader.isDTD ( self )

返回 true 若 tokenType () 等于 DTD ;否则返回 false.

bool QXmlStreamReader.isEndDocument ( self )

返回 true 若 tokenType () 等于 EndDocument ;否则 returns false.

bool QXmlStreamReader.isEndElement ( self )

返回 true 若 tokenType () 等于 EndElement ;否则 returns false.

bool QXmlStreamReader.isEntityReference ( self )

返回 true 若 tokenType () 等于 EntityReference ; otherwise returns false.

bool QXmlStreamReader.isProcessingInstruction ( self )

返回 true 若 tokenType () 等于 ProcessingInstruction ; otherwise returns false.

bool QXmlStreamReader.isStandaloneDocument ( self )

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

若未剖析 XML 声明,此函数返回 false.

bool QXmlStreamReader.isStartDocument ( self )

返回 true 若 tokenType () 等于 StartDocument ;否则 returns false.

bool QXmlStreamReader.isStartElement ( self )

返回 true 若 tokenType () 等于 StartElement ;否则 returns false.

bool QXmlStreamReader.isWhitespace ( self )

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

另请参阅 isCharacters () 和 text ().

int QXmlStreamReader.lineNumber ( self )

返回当前行号,从 1 开始。

另请参阅 columnNumber () 和 characterOffset ().

QStringRef QXmlStreamReader.name ( self )

返回本地名称为 StartElement , EndElement ,或 EntityReference .

另请参阅 namespaceUri () 和 qualifiedName ().

list-of-QXmlStreamNamespaceDeclaration QXmlStreamReader.namespaceDeclarations ( self )

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

QXmlStreamNamespaceDeclaration class is defined to be a QVector of QXmlStreamNamespaceDeclaration .

另请参阅 addExtraNamespaceDeclaration () and addExtraNamespaceDeclarations ().

bool QXmlStreamReader.namespaceProcessing ( self )

QStringRef QXmlStreamReader.namespaceUri ( self )

返回 namespaceUri 为 StartElement or EndElement .

另请参阅 name () and qualifiedName ().

list-of-QXmlStreamNotationDeclaration QXmlStreamReader.notationDeclarations ( self )

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

QXmlStreamNotationDeclarations class is defined to be a QVector of QXmlStreamNotationDeclaration .

QStringRef QXmlStreamReader.prefix ( self )

返回前缀为 StartElement or EndElement .

该函数在 Qt 4.4 引入。

另请参阅 name () and qualifiedName ().

QStringRef QXmlStreamReader.processingInstructionData ( self )

返回数据为 ProcessingInstruction .

QStringRef QXmlStreamReader.processingInstructionTarget ( self )

Returns the target of a ProcessingInstruction .

QStringRef QXmlStreamReader.qualifiedName ( self )

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 () 和 attribute's local name ().

另请参阅 name (), prefix (),和 namespaceUri ().

QXmlStreamReader.raiseError ( self , QString  message  = QString())

引发自定义错误采用可选错误 message .

另请参阅 error () 和 errorString ().

QString QXmlStreamReader.readElementText ( self )

Convenience function to be called in case a StartElement was read. Reads until the corresponding EndElement 并返回 all text in-between. In case of no error, the current token (see tokenType ()) after having called this function is EndElement .

函数串联 text () 当它读取 Characters or EntityReference 令牌,但跳过 ProcessingInstruction and Comment 。若 the current token is not StartElement ,空 string is returned.

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 引入。

QString QXmlStreamReader.readElementText ( self , ReadElementTextBehaviour   behaviour )

此函数重载 readElementText ().

调用此函数相当于调用 readElementText( ErrorOnUnexpectedElement ).

TokenType QXmlStreamReader.readNext ( self )

读取下一令牌并返回其类型。

With one exception, once an error () is reported by readNext(), further reading of the XML stream is not possible. Then atEnd () returns true, hasError () 返回 true, and this function returns QXmlStreamReader.Invalid .

The exception is when error () 返回 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 () 到 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 ().

bool QXmlStreamReader.readNextStartElement ( self )

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.

You can traverse a document by repeatedly calling this function while ensuring that the stream reader is not at the end of the document:

 QXmlStreamReader xs(&file);
 while (!xs.atEnd()) {
     if (xs.readNextStartElement())
         std.cout << qPrintable(xs.name().toString()) << std.endl;
 }
			

This is a convenience function for when you're only concerned with parsing XML elements. The QXmlStream 书签范例 makes extensive use of this function.

该函数在 Qt 4.6 引入。

另请参阅 readNext ().

QXmlStreamReader.setDevice ( self , QIODevice   device )

把当前设备设为 device . Setting the device resets the stream to its initial state.

另请参阅 device () 和 clear ().

QXmlStreamReader.setEntityResolver ( self , QXmlStreamEntityResolver   resolver )

Makes resolver the new entityResolver ().

The stream reader does not take ownership of the resolver. It's the callers responsibility to ensure that the resolver is valid during the entire life-time of the stream reader object, or until another resolver or 0 is set.

该函数在 Qt 4.4 引入。

另请参阅 entityResolver ().

QXmlStreamReader.setNamespaceProcessing ( self , bool)

QXmlStreamReader.skipCurrentElement ( self )

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 引入。

QStringRef QXmlStreamReader.text ( self )

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

QString QXmlStreamReader.tokenString ( self )

以字符串形式返回读取器的当前令牌。

另请参阅 tokenType ().

TokenType QXmlStreamReader.tokenType ( self )

返回当前令牌类型。

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

另请参阅 tokenString ().