Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QXmlStreamReader Class

TheQXmlStreamReader class provides a fast parser for reading well-formed XML via a simple streaming API.More...

Header:#include <QXmlStreamReader>
Since: Qt 4.3
Inherited By:

Note: All functions in this class arereentrant.

Public Types

enumError { NoError, CustomError, NotWellFormedError, PrematureEndOfDocumentError, UnexpectedElementError }
enumReadElementTextBehaviour { ErrorOnUnexpectedElement, IncludeChildElements, SkipChildElements }
enumTokenType { NoToken, Invalid, StartDocument, EndDocument, ..., ProcessingInstruction }

Properties

Public Functions

QXmlStreamReader()
QXmlStreamReader(QIODevice * device)
QXmlStreamReader(const QByteArray & data)
QXmlStreamReader(const QString & data)
QXmlStreamReader(const char * data)
~QXmlStreamReader()
voidaddData(const QByteArray & data)
voidaddData(const QString & data)
voidaddData(const char * data)
voidaddExtraNamespaceDeclaration(const QXmlStreamNamespaceDeclaration & extraNamespaceDeclaration)
voidaddExtraNamespaceDeclarations(const QXmlStreamNamespaceDeclarations & extraNamespaceDeclarations)
boolatEnd() const
QXmlStreamAttributesattributes() const
qint64characterOffset() const
voidclear()
qint64columnNumber() const
QIODevice *device() const
QStringRefdocumentEncoding() const
QStringRefdocumentVersion() const
QStringRefdtdName() const
QStringRefdtdPublicId() const
QStringRefdtdSystemId() const
QXmlStreamEntityDeclarationsentityDeclarations() const
QXmlStreamEntityResolver *entityResolver() const
Errorerror() const
QStringerrorString() const
boolhasError() const
boolisCDATA() const
boolisCharacters() const
boolisComment() const
boolisDTD() const
boolisEndDocument() const
boolisEndElement() const
boolisEntityReference() const
boolisProcessingInstruction() const
boolisStandaloneDocument() const
boolisStartDocument() const
boolisStartElement() const
boolisWhitespace() const
qint64lineNumber() const
QStringRefname() const
QXmlStreamNamespaceDeclarationsnamespaceDeclarations() const
boolnamespaceProcessing() const
QStringRefnamespaceUri() const
QXmlStreamNotationDeclarationsnotationDeclarations() const
QStringRefprefix() const
QStringRefprocessingInstructionData() const
QStringRefprocessingInstructionTarget() const
QStringRefqualifiedName() const
voidraiseError(const QString & message = QString())
QStringreadElementText(ReadElementTextBehaviour behaviour)
QStringreadElementText()
TokenTypereadNext()
boolreadNextStartElement()
voidsetDevice(QIODevice * device)
voidsetEntityResolver(QXmlStreamEntityResolver * resolver)
voidsetNamespaceProcessing(bool)
voidskipCurrentElement()
QStringReftext() const
QStringtokenString() const
TokenTypetokenType() const

Detailed Description

TheQXmlStreamReader 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 (seeQXmlSimpleReader). In some cases it might also be a faster and more convenient alternative for use in applications that would otherwise use a DOM tree (seeQDomDocument).QXmlStreamReader reads data either from aQIODevice (seesetDevice()), or from a rawQByteArray (seeaddData()).

Qt providesQXmlStreamWriter 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 betweenQXmlStreamReader and SAX ishow these XML tokens are reported. With SAX, the application must provide handlers (callback functions) that receive so-called XMLevents from the parser at the parser's convenience. WithQXmlStreamReader, the application code itself drives the loop and pullstokens from the reader, one after another, as it needs them. This is done by callingreadNext(), where the reader reads from the input stream until it completes the next token, at which point it returns thetokenType(). A set of convenient functions includingisStartElement() andtext() can then be used to examine the token to obtain information about what has been read. The big advantage of thispulling 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 withQXmlStreamReader 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 doesnot 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() andhasError() return true, anderror() returns the error that occurred. The functionserrorString(),lineNumber(),columnNumber(), andcharacterOffset() are for constructing an appropriate error or warning message. To simplify application code,QXmlStreamReader contains araiseError() mechanism that lets you raise custom errors that trigger the same error handling described.

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

Namespaces

QXmlStream understands and resolves XML namespaces. E.g. in case of aStartElement,namespaceUri() returns the namespace the element is in, andname() returns the element'slocal name. The combination ofnamespaceUri and name uniquely identifies an element. If a namespace prefix was not declared in the XML entities parsed by the reader, thenamespaceUri 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'squalifiedName() instead. A qualified name is the element'sprefix() followed by colon followed by the element's localname() - exactly like the element appears in the raw XML data. Since the mappingnamespaceUri 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 thenamespaceProcessing property.

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 aPrematureEndOfDocumentError. When more data arrives, either because of a call toaddData() or because more data is available through the networkdevice(), the reader recovers from thePrematureEndOfDocumentError error and continues parsing the new data with the next call toreadNext().

For example, if your application reads data from the network using anetwork access manager, you would issue anetwork request to the manager and receive anetwork reply in return. Since aQNetworkReply is aQIODevice, you connect itsreadyRead() signal to a custom slot, e.g.slotReadyRead() in the code snippet shown in the discussion forQNetworkAccessManager. In this slot, you read all available data withreadAll() and pass it to the XML stream reader usingaddData(). 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 asQStringRef rather than realQString objects.QStringRef is a thin wrapper aroundQString substrings that provides a subset of theQString API without the memory allocation and reference-counting overhead. CallingtoString() on any of those objects returns an equivalent realQString object.

Member Type Documentation

enum QXmlStreamReader::Error

This enum specifies different error cases

ConstantValueDescription
QXmlStreamReader::NoError0No error has occurred.
QXmlStreamReader::CustomError2A custom error has been raised withraiseError()
QXmlStreamReader::NotWellFormedError3The parser internally raised an error due to the read XML not being well-formed.
QXmlStreamReader::PrematureEndOfDocumentError4The 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 callingaddData() or by waiting for it to arrive on thedevice().
QXmlStreamReader::UnexpectedElementError1The parser encountered an element that was different to those it expected.

enum QXmlStreamReader::ReadElementTextBehaviour

This enum specifies the different behaviours ofreadElementText().

ConstantValueDescription
QXmlStreamReader::ErrorOnUnexpectedElement0Raise anUnexpectedElementError and return what was read so far when a child element is encountered.
QXmlStreamReader::IncludeChildElements1Recursively include the text from child elements.
QXmlStreamReader::SkipChildElements2Skip child elements.

This enum was introduced or modified in Qt 4.6.

enum QXmlStreamReader::TokenType

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

ConstantValueDescription
QXmlStreamReader::NoToken0The reader has not yet read anything.
QXmlStreamReader::Invalid1An error has occurred, reported inerror() anderrorString().
QXmlStreamReader::StartDocument2The reader reports the XML version number indocumentVersion(), and the encoding as specified in the XML document indocumentEncoding(). If the document is declared standalone,isStandaloneDocument() returns true; otherwise it returns false.
QXmlStreamReader::EndDocument3The reader reports the end of the document.
QXmlStreamReader::StartElement4The reader reports the start of an element withnamespaceUri() andname(). Empty elements are also reported as StartElement, followed directly by EndElement. The convenience functionreadElementText() can be called to concatenate all content until the corresponding EndElement. Attributes are reported inattributes(), namespace declarations innamespaceDeclarations().
QXmlStreamReader::EndElement5The reader reports the end of an element withnamespaceUri() andname().
QXmlStreamReader::Characters6The reader reports characters intext(). If the characters are all white-space,isWhitespace() returns true. If the characters stem from a CDATA section,isCDATA() returns true.
QXmlStreamReader::Comment7The reader reports a comment intext().
QXmlStreamReader::DTD8The reader reports a DTD intext(), notation declarations innotationDeclarations(), and entity declarations inentityDeclarations(). Details of the DTD declaration are reported in indtdName(),dtdPublicId(), anddtdSystemId().
QXmlStreamReader::EntityReference9The reader reports an entity reference that could not be resolved. The name of the reference is reported inname(), the replacement text intext().
QXmlStreamReader::ProcessingInstruction10The reader reports a processing instruction inprocessingInstructionTarget() andprocessingInstructionData().

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 enabled.

Access functions:

boolnamespaceProcessing() const
voidsetNamespaceProcessing(bool)

Member Function Documentation

QXmlStreamReader::QXmlStreamReader()

Constructs a stream reader.

See alsosetDevice() andaddData().

QXmlStreamReader::QXmlStreamReader(QIODevice * device)

Creates a new stream reader that reads fromdevice.

See alsosetDevice() andclear().

QXmlStreamReader::QXmlStreamReader(constQByteArray & data)

Creates a new stream reader that reads fromdata.

See alsoaddData(),clear(), andsetDevice().

QXmlStreamReader::QXmlStreamReader(constQString & data)

Creates a new stream reader that reads fromdata.

See alsoaddData(),clear(), andsetDevice().

QXmlStreamReader::QXmlStreamReader(constchar * data)

Creates a new stream reader that reads fromdata.

See alsoaddData(),clear(), andsetDevice().

QXmlStreamReader::~QXmlStreamReader()

Destructs the reader.

void QXmlStreamReader::addData(constQByteArray & data)

Adds moredata for the reader to read. This function does nothing if the reader has adevice().

See alsoreadNext() andclear().

void QXmlStreamReader::addData(constQString & data)

Adds moredata for the reader to read. This function does nothing if the reader has adevice().

See alsoreadNext() andclear().

void QXmlStreamReader::addData(constchar * data)

Adds moredata for the reader to read. This function does nothing if the reader has adevice().

See alsoreadNext() andclear().

void QXmlStreamReader::addExtraNamespaceDeclaration(constQXmlStreamNamespaceDeclaration & extraNamespaceDeclaration)

Adds anextraNamespaceDeclaration. 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.

This function was introduced in Qt 4.4.

See alsonamespaceDeclarations(),addExtraNamespaceDeclarations(), andsetNamespaceProcessing().

void QXmlStreamReader::addExtraNamespaceDeclarations(constQXmlStreamNamespaceDeclarations & extraNamespaceDeclarations)

Adds a vector of declarations specified byextraNamespaceDeclarations.

This function was introduced in Qt 4.4.

See alsonamespaceDeclarations() andaddExtraNamespaceDeclaration().

bool QXmlStreamReader::atEnd() const

Returns true if the reader has read until the end of the XML document, or if anerror() has occurred and reading has been aborted. Otherwise, it returns false.

When atEnd() andhasError() return true anderror() returnsPrematureEndOfDocumentError, 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 withaddData(), if the XML is being read from aQByteArray, or by waiting for more data to arrive if the XML is being read from aQIODevice. Either way, atEnd() will return false once more data is available.

See alsohasError(),error(),device(), andQIODevice::atEnd().

QXmlStreamAttributes QXmlStreamReader::attributes() const

Returns the attributes of aStartElement.

qint64 QXmlStreamReader::characterOffset() const

Returns the current character offset, starting with 0.

See alsolineNumber() andcolumnNumber().

void QXmlStreamReader::clear()

Removes anydevice() or data from the reader and resets its internal state to the initial state.

See alsoaddData().

qint64 QXmlStreamReader::columnNumber() const

Returns the current column number, starting with 0.

See alsolineNumber() andcharacterOffset().

QIODevice * QXmlStreamReader::device() const

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

See alsosetDevice().

QStringRef QXmlStreamReader::documentEncoding() const

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

This function was introduced in Qt 4.4.

QStringRef QXmlStreamReader::documentVersion() const

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

This function was introduced in Qt 4.4.

QStringRef QXmlStreamReader::dtdName() const

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

This function was introduced in Qt 4.4.

QStringRef QXmlStreamReader::dtdPublicId() const

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

This function was introduced in Qt 4.4.

QStringRef QXmlStreamReader::dtdSystemId() const

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

This function was introduced in Qt 4.4.

QXmlStreamEntityDeclarations QXmlStreamReader::entityDeclarations() const

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

TheQXmlStreamEntityDeclarations class is defined to be aQVector ofQXmlStreamEntityDeclaration.

QXmlStreamEntityResolver * QXmlStreamReader::entityResolver() const

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

This function was introduced in Qt 4.4.

See alsosetEntityResolver().

Error QXmlStreamReader::error() const

Returns the type of the current error, orNoError if no error occurred.

See alsoerrorString() andraiseError().

QString QXmlStreamReader::errorString() const

Returns the error message that was set withraiseError().

See alsoerror(),lineNumber(),columnNumber(), andcharacterOffset().

bool QXmlStreamReader::hasError() const

Returnstrue if an error has occurred, otherwisefalse.

See alsoerrorString() anderror().

bool QXmlStreamReader::isCDATA() const

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

See alsoisCharacters() andtext().

bool QXmlStreamReader::isCharacters() const

Returns true iftokenType() equalsCharacters; otherwise returns false.

See alsoisWhitespace() andisCDATA().

bool QXmlStreamReader::isComment() const

Returns true iftokenType() equalsComment; otherwise returns false.

bool QXmlStreamReader::isDTD() const

Returns true iftokenType() equalsDTD; otherwise returns false.

bool QXmlStreamReader::isEndDocument() const

Returns true iftokenType() equalsEndDocument; otherwise returns false.

bool QXmlStreamReader::isEndElement() const

Returns true iftokenType() equalsEndElement; otherwise returns false.

bool QXmlStreamReader::isEntityReference() const

Returns true iftokenType() equalsEntityReference; otherwise returns false.

bool QXmlStreamReader::isProcessingInstruction() const

Returns true iftokenType() equalsProcessingInstruction; 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 iftokenType() equalsStartDocument; otherwise returns false.

bool QXmlStreamReader::isStartElement() const

Returns true iftokenType() equalsStartElement; otherwise returns false.

bool QXmlStreamReader::isWhitespace() const

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

See alsoisCharacters() andtext().

qint64 QXmlStreamReader::lineNumber() const

Returns the current line number, starting with 1.

See alsocolumnNumber() andcharacterOffset().

QStringRef QXmlStreamReader::name() const

Returns the local name of aStartElement,EndElement, or anEntityReference.

See alsonamespaceUri() andqualifiedName().

QXmlStreamNamespaceDeclarations QXmlStreamReader::namespaceDeclarations() const

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

TheQXmlStreamNamespaceDeclaration class is defined to be aQVector ofQXmlStreamNamespaceDeclaration.

See alsoaddExtraNamespaceDeclaration() andaddExtraNamespaceDeclarations().

QStringRef QXmlStreamReader::namespaceUri() const

Returns the namespaceUri of aStartElement orEndElement.

See alsoname() andqualifiedName().

QXmlStreamNotationDeclarations QXmlStreamReader::notationDeclarations() const

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

TheQXmlStreamNotationDeclarations class is defined to be aQVector ofQXmlStreamNotationDeclaration.

QStringRef QXmlStreamReader::prefix() const

Returns the prefix of aStartElement orEndElement.

This function was introduced in Qt 4.4.

See alsoname() andqualifiedName().

QStringRef QXmlStreamReader::processingInstructionData() const

Returns the data of aProcessingInstruction.

QStringRef QXmlStreamReader::processingInstructionTarget() const

Returns the target of aProcessingInstruction.

QStringRef QXmlStreamReader::qualifiedName() const

Returns the qualified name of aStartElement orEndElement;

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 resolvednamespaceUri() and the attribute's localname().

See alsoname(),prefix(), andnamespaceUri().

void QXmlStreamReader::raiseError(constQString & message = QString())

Raises a custom error with an optional errormessage.

See alsoerror() anderrorString().

QString QXmlStreamReader::readElementText(ReadElementTextBehaviour behaviour)

Convenience function to be called in case aStartElement was read. Reads until the correspondingEndElement and returns all text in-between. In case of no error, the current token (seetokenType()) after having called this function isEndElement.

The function concatenatestext() when it reads eitherCharacters orEntityReference tokens, but skipsProcessingInstruction andComment. If the current token is notStartElement, an empty string is returned.

Thebehaviour defines what happens in case anything else is read before reachingEndElement. The function can include the text from child elements (useful for example for HTML), ignore child elements, or raise anUnexpectedElementError and return what was read so far.

This function was introduced in Qt 4.6.

QString QXmlStreamReader::readElementText()

This function overloadsreadElementText().

Calling this function is equivalent to callingreadElementText(ErrorOnUnexpectedElement).

TokenType QXmlStreamReader::readNext()

Reads the next token and returns its type.

With one exception, once anerror() is reported by readNext(), further reading of the XML stream is not possible. ThenatEnd() returns true,hasError() returns true, and this function returnsQXmlStreamReader::Invalid.

The exception is whenerror() returnsPrematureEndOfDocumentError. 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, parsingcan be resumed by callingaddData() to add the next chunk of XML, when the stream is being read from aQByteArray, or by waiting for more data to arrive when the stream is being read from adevice().

See alsotokenType() andtokenString().

bool QXmlStreamReader::readNextStartElement()

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. TheQXmlStream Bookmarks Example makes extensive use of this function.

This function was introduced in Qt 4.6.

See alsoreadNext().

void QXmlStreamReader::setDevice(QIODevice * device)

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

See alsodevice() andclear().

void QXmlStreamReader::setEntityResolver(QXmlStreamEntityResolver * resolver)

Makesresolver the newentityResolver().

The stream reader doesnot 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.

This function was introduced in Qt 4.4.

See alsoentityResolver().

void QXmlStreamReader::skipCurrentElement()

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.

This function was introduced in Qt 4.6.

QStringRef QXmlStreamReader::text() const

Returns the text ofCharacters,Comment,DTD, orEntityReference.

QString QXmlStreamReader::tokenString() const

Returns the reader's current token as string.

See alsotokenType().

TokenType QXmlStreamReader::tokenType() const

Returns the type of the current token.

The current token can also be queried with the convenience functionsisStartDocument(),isEndDocument(),isStartElement(),isEndElement(),isCharacters(),isComment(),isDTD(),isEntityReference(), andisProcessingInstruction().

See alsotokenString().

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp