QXmlStreamReader Class
The QXmlStreamReader class provides a fast parser for reading well-formed XML. More…
| Header | #include <QXmlStreamReader> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Core) |
| Module | Nt Core C++ Classes |
List of all members, including inherited members
Public Types
| enum | TokenType |
| enum | ReadElementTextBehaviour |
| enum | Error |
Public Functions
Detailed Description
The reader reads a document as a stream of tokens. The program asks for the next token with readNext(), looks at what it is, and asks for the next: it pulls the tokens, which lets the code that reads a document be shaped like the document.
QXmlStreamReader xml(&file);
if (xml.readNextStartElement() && xml.name() == u"library") {
while (xml.readNextStartElement()) {
if (xml.name() == u"book")
addBook(xml.attributes().value("isbn").toString(), xml.readElementText());
else
xml.skipCurrentElement();
}
}
if (xml.hasError())
qWarning() << xml.errorString() << "at line" << xml.lineNumber();
The reader takes a device, or data that the program adds with addData(), also piece by piece as it arrives from a network: see readNext(). It checks that the document is well-formed and stops with an error at the first place where it is not.
Namespaces are processed unless setNamespaceProcessing() turns that off. The references to characters and to the entities that the document declares are replaced in text() and in the values of attributes.
See also QXmlStreamWriter and QXmlStreamAttributes.
Differences from Qt
The functions that take text take a const QString &; there are no QAnyStringView overloads. Bytes are decoded as UTF-8, UTF-16 or Latin-1; a declaration that names another encoding is an error. The document type definition is read for its entities and notations only: attribute defaults are not applied, so QXmlStreamAttribute::isDefault() is always false, and parameter entities are not expanded. External entities are never fetched, and QXmlStreamEntityResolver::resolveEntity() is not called. Where the text of an entity is put into the document, lineNumber() and columnNumber() count its characters too. After the end of the document, readNext() returns Invalid without an error. The names of elements are checked against a simplified set of the characters that XML allows in a name.
Member Type Documentation
enum QXmlStreamReader::Error
The kinds of error that the reader reports.
| Constant | Description |
|---|---|
QXmlStreamReader::NoError | No error has occurred. |
QXmlStreamReader::UnexpectedElementError | The reader met an element where it expected something else. |
QXmlStreamReader::CustomError | The program raised the error with raiseError(). |
QXmlStreamReader::NotWellFormedError | The document is not well-formed XML. |
QXmlStreamReader::PrematureEndOfDocumentError | The input ended before the document did. Add more data and go on. |
enum QXmlStreamReader::ReadElementTextBehaviour
What readElementText() does when the element has child elements.
| Constant | Description |
|---|---|
QXmlStreamReader::ErrorOnUnexpectedElement | Raise UnexpectedElementError and return what was read so far. |
QXmlStreamReader::IncludeChildElements | Add the text of the child elements to the result. |
QXmlStreamReader::SkipChildElements | Leave the child elements and their text out. |
enum QXmlStreamReader::TokenType
The kinds of token that readNext() reports.
| Constant | Description |
|---|---|
QXmlStreamReader::NoToken | The reader has not read anything yet. |
QXmlStreamReader::Invalid | An error has occurred; see error() and errorString(). |
QXmlStreamReader::StartDocument | The start of the document, with documentVersion() and documentEncoding() if it has an XML declaration. |
QXmlStreamReader::EndDocument | The end of the document. |
QXmlStreamReader::StartElement | The start of an element, with its name(), namespaceUri(), attributes() and namespaceDeclarations(). An empty-element tag is reported as a start and an end. |
QXmlStreamReader::EndElement | The end of an element, with its name() and namespaceUri(). |
QXmlStreamReader::Characters | Text, in text(). isWhitespace() and isCDATA() say more about it. |
QXmlStreamReader::Comment | A comment, in text(). |
QXmlStreamReader::DTD | The document type definition, as written in text(), with dtdName(), notationDeclarations() and entityDeclarations(). |
QXmlStreamReader::EntityReference | A reference to an entity that could not be replaced, with the name of the entity in name(). |
QXmlStreamReader::ProcessingInstruction | A processing instruction, with processingInstructionTarget() and processingInstructionData(). |
Member Function Documentation
QXmlStreamReader::QXmlStreamReader()
Constructs a reader without input. Give it a device with setDevice() or data with addData().
QXmlStreamReader::QXmlStreamReader(QIODevice *device)
Constructs a reader that reads from device, which must be open for reading.
See also setDevice().
QXmlStreamReader::QXmlStreamReader(const QByteArray &data)
Constructs a reader that reads data. The encoding is found from the byte order mark or the XML declaration, and is UTF-8 without them.
See also addData().
QXmlStreamReader::QXmlStreamReader(const QString &data)
Constructs a reader that reads the text data. An encoding that its XML declaration names is reported and otherwise ignored.
QXmlStreamReader::QXmlStreamReader(const char *data)
Constructs a reader that reads the null-terminated data.
QXmlStreamReader::~QXmlStreamReader()
Destroys the reader. The device is not closed or deleted.
void QXmlStreamReader::addData(const QByteArray &data)
Adds data to the end of the document. Use this to parse a document that arrives in pieces: when readNext() reports PrematureEndOfDocumentError, add the next piece and call readNext() again. A reader that has a device ignores the data.
See also readNext() and clear().
void QXmlStreamReader::addData(const QString &data)
This is an overloaded function.
Adds the text data to the end of the document.
void QXmlStreamReader::addData(const char *data)
This is an overloaded function.
Adds the null-terminated data to the end of the document.
void QXmlStreamReader::addExtraNamespaceDeclaration(const QXmlStreamNamespaceDeclaration &extraNamespaceDeclaraction)
Adds extraNamespaceDeclaraction to the namespaces that the reader knows, as if the document had declared it on an element around the root. Use this to read a fragment whose prefixes are declared elsewhere.
See also addExtraNamespaceDeclarations() and namespaceDeclarations().
void QXmlStreamReader::addExtraNamespaceDeclarations(const QXmlStreamNamespaceDeclarations &extraNamespaceDeclaractions)
Adds each of extraNamespaceDeclaractions as addExtraNamespaceDeclaration() does.
bool QXmlStreamReader::atEnd() const
Returns true if the reader has read up to the end of the document, or if an error has stopped it. After a PrematureEndOfDocumentError the reader is at the end only until more data arrives.
See also tokenType() and error().
QXmlStreamAttributes QXmlStreamReader::attributes() const
Returns the attributes of the current start element, without its namespace declarations.
See also namespaceDeclarations().
qint64 QXmlStreamReader::characterOffset() const
Returns the number of characters that the reader has read in all, counted in UTF-16 code units after line ends have been made single line feeds.
See also lineNumber() and columnNumber().
void QXmlStreamReader::clear()
Forgets the document and the device, and puts the reader back into the state of a new one. The namespace processing, the entity resolver and the entity expansion limit are kept.
See also addData() and setDevice().
qint64 QXmlStreamReader::columnNumber() const
Returns the number of characters that the reader has read on the current line.
See also lineNumber() and characterOffset().
QIODevice * QXmlStreamReader::device() const
Returns the device that the reader reads from, or nullptr if it reads data that was added.
See also setDevice().
QStringView QXmlStreamReader::documentEncoding() const
Returns the encoding that the XML declaration names, or an empty view if it names none.
QStringView QXmlStreamReader::documentVersion() const
Returns the version that the XML declaration gives, which is 1.0, or an empty view if the document has no declaration.
QStringView QXmlStreamReader::dtdName() const
Returns the name that the document type definition gives the root element.
See also dtdPublicId() and dtdSystemId().
QStringView QXmlStreamReader::dtdPublicId() const
Returns the public identifier of the document type definition, or an empty view.
See also dtdName() and dtdSystemId().
QStringView QXmlStreamReader::dtdSystemId() const
Returns the system identifier of the document type definition, or an empty view.
See also dtdName() and dtdPublicId().
QXmlStreamEntityDeclarations QXmlStreamReader::entityDeclarations() const
Returns the unparsed entities that the document type definition declares: those that are external and have a notation. They are known once the token of the definition has been read.
See also notationDeclarations().
int QXmlStreamReader::entityExpansionLimit() const
Returns the largest number of characters that one entity reference may expand to. The default is 4096.
This function was introduced in 5.15.
See also setEntityExpansionLimit().
QXmlStreamEntityResolver * QXmlStreamReader::entityResolver() const
Returns the entity resolver, or nullptr if there is none.
See also setEntityResolver().
Error QXmlStreamReader::error() const
Returns the kind of error that has occurred, or NoError.
See also errorString() and raiseError().
QString QXmlStreamReader::errorString() const
Returns a text for the error that has occurred, or an empty string. Add lineNumber() and columnNumber() to tell the user where.
See also error().
bool QXmlStreamReader::hasError() const
Returns true if an error has occurred.
See also error() and errorString().
bool QXmlStreamReader::hasStandaloneDeclaration() const
Returns true if the XML declaration says whether the document is standalone, with yes or no.
This function was introduced in 6.6.
See also isStandaloneDocument().
bool QXmlStreamReader::isCDATA() const
Returns true if the current token is characters that came from a CDATA section.
See also isCharacters() and text().
bool QXmlStreamReader::isCharacters() const
Returns true if tokenType() is Characters.
See also isWhitespace() and isCDATA().
bool QXmlStreamReader::isComment() const
Returns true if tokenType() is Comment.
bool QXmlStreamReader::isDTD() const
Returns true if tokenType() is DTD.
bool QXmlStreamReader::isEndDocument() const
Returns true if tokenType() is EndDocument.
bool QXmlStreamReader::isEndElement() const
Returns true if tokenType() is EndElement.
bool QXmlStreamReader::isEntityReference() const
Returns true if tokenType() is EntityReference.
bool QXmlStreamReader::isProcessingInstruction() const
Returns true if tokenType() is ProcessingInstruction.
bool QXmlStreamReader::isStandaloneDocument() const
Returns true if the XML declaration says that the document is standalone. A document without that declaration is not.
See also hasStandaloneDeclaration().
bool QXmlStreamReader::isStartDocument() const
Returns true if tokenType() is StartDocument.
bool QXmlStreamReader::isStartElement() const
Returns true if tokenType() is StartElement.
bool QXmlStreamReader::isWhitespace() const
Returns true if the current token is characters that are all white space.
See also isCharacters() and text().
qint64 QXmlStreamReader::lineNumber() const
Returns the number of the line that the reader has read up to, starting with 1.
See also columnNumber() and characterOffset().
QStringView QXmlStreamReader::name() const
Returns the local name of the current start or end element, or the name of the entity of an entity reference.
See also qualifiedName() and namespaceUri().
QXmlStreamNamespaceDeclarations QXmlStreamReader::namespaceDeclarations() const
Returns the namespaces that the current start element declares.
See also addExtraNamespaceDeclaration().
bool QXmlStreamReader::namespaceProcessing() const
Returns true if namespaces are processed.
See also setNamespaceProcessing().
QStringView QXmlStreamReader::namespaceUri() const
Returns the namespace URI of the current start or end element, or an empty view if it is in no namespace.
QXmlStreamNotationDeclarations QXmlStreamReader::notationDeclarations() const
Returns the notations that the document type definition declares. They are known once the token of the definition has been read.
See also entityDeclarations().
QStringView QXmlStreamReader::prefix() const
Returns the prefix of the current start or end element, or an empty view if it has none.
See also name() and qualifiedName().
QStringView QXmlStreamReader::processingInstructionData() const
Returns the data of the current processing instruction, which is what follows the target.
See also processingInstructionTarget().
QStringView QXmlStreamReader::processingInstructionTarget() const
Returns the target of the current processing instruction.
See also processingInstructionData().
QStringView QXmlStreamReader::qualifiedName() const
Returns the name of the current start or end element as it is written, with its prefix.
void QXmlStreamReader::raiseError(const QString &message = QString())
Raises the error CustomError with the text message, which ends the reading: atEnd() becomes true and readNext() returns Invalid. Use it to stop on a document that is well-formed but not what the program expects, so that one place handles all errors.
See also error() and errorString().
QString QXmlStreamReader::readElementText(ReadElementTextBehaviour behaviour = ErrorOnUnexpectedElement)
Reads the text of the current start element up to its end element and returns it. Comments and processing instructions inside are left out. What happens at a child element depends on behaviour: by default it is the error UnexpectedElementError.
Afterwards the current token is the end element. If the current token is not a start element, the function raises an error and returns an empty string.
See also readNextStartElement().
TokenType QXmlStreamReader::readNext()
Reads the next token and returns its type. The functions that describe a token, such as name() and text(), then describe this one, and the views they returned for the token before are no longer valid.
When the input ends in the middle of the document, the type is Invalid and error() is PrematureEndOfDocumentError; after more data has been added, or the device has more, the next call goes on where the document stopped. Any other error ends the reading: every later call returns Invalid.
See also tokenType() and tokenString().
bool QXmlStreamReader::readNextStartElement()
Reads until the next start element inside the current element. Returns true when it has found one, and false when it reached the end of the current element first, or the end of the document or an error. Use it to walk the children of an element:
while (xml.readNextStartElement()) {
if (xml.name() == u"title")
title = xml.readElementText();
else
xml.skipCurrentElement();
}
See also skipCurrentElement() and readNext().
void QXmlStreamReader::setDevice(QIODevice *device)
Makes the reader read from device, which must be open for reading, and forget the document it was reading.
See also device() and clear().
void QXmlStreamReader::setEntityExpansionLimit(int limit)
Sets the largest number of characters that one entity reference may expand to, counting the entities that it refers to in turn, to limit. A document that goes over it is not well-formed. The limit keeps a small document from growing without bound in memory.
This function was introduced in 5.15.
See also entityExpansionLimit().
void QXmlStreamReader::setEntityResolver(QXmlStreamEntityResolver *resolver)
Makes the reader ask resolver about entities that the document does not declare. The reader does not own the resolver.
See also entityResolver().
void QXmlStreamReader::setNamespaceProcessing(bool enable)
Turns namespace processing on or off, according to enable. It is on by default. With it, the xmlns attributes of an element are its namespaceDeclarations() and not among its attributes(), and names are split into prefix() and name() and given a namespaceUri(). Without it, a name is all local name, colons included.
See also namespaceProcessing().
void QXmlStreamReader::skipCurrentElement()
Reads up to the end of the current element, skipping everything inside it. Call it when the current token is a start element that the program has no use for.
See also readNextStartElement().
QStringView QXmlStreamReader::text() const
Returns the text of the current characters, comment or document type definition. For characters, the references are replaced and line ends are line feeds; for the definition it is the whole declaration as written.
See also isWhitespace() and isCDATA().
QString QXmlStreamReader::tokenString() const
Returns the name of the type of the current token, such as "StartElement".
See also tokenType().
TokenType QXmlStreamReader::tokenType() const
Returns the type of the token that readNext() read last.
See also tokenString().