QXmlStreamWriter 類

The QXmlStreamWriter class provides an XML 1.0 writer with a simple streaming API. 更多...

頭: #include <QXmlStreamWriter>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

注意: 此類的所有函數 可重入 .

公共類型

(從 6.10 起) 枚舉類 Error { None, IO, Encoding, InvalidCharacter, Custom }

特性

公共函數

QXmlStreamWriter ()
QXmlStreamWriter (QByteArray * array )
QXmlStreamWriter (QIODevice * device )
QXmlStreamWriter (QString * string )
~QXmlStreamWriter ()
bool autoFormatting () const
int autoFormattingIndent () const
QIODevice * device () const
(從 6.10 起) QXmlStreamWriter::Error error () const
(從 6.10 起) QString errorString () const
bool hasError () const
(從 6.10 起) void raiseError (QAnyStringView message )
void setAutoFormatting (bool enable )
void setAutoFormattingIndent (int spacesOrTabs )
void setDevice (QIODevice * device )
void setStopWritingOnError (bool stop )
bool stopWritingOnError () const
void writeAttribute (QAnyStringView namespaceUri , QAnyStringView name , QAnyStringView value )
void writeAttribute (const QXmlStreamAttribute & attribute )
void writeAttribute (QAnyStringView qualifiedName , QAnyStringView value )
void writeAttributes (const QXmlStreamAttributes & 屬性 )
void writeCDATA (QAnyStringView text )
void writeCharacters (QAnyStringView text )
void writeComment (QAnyStringView text )
void writeCurrentToken (const QXmlStreamReader & reader )
void writeDTD (QAnyStringView dtd )
void writeDefaultNamespace (QAnyStringView namespaceUri )
void writeEmptyElement (QAnyStringView namespaceUri , QAnyStringView name )
void writeEmptyElement (QAnyStringView qualifiedName )
void writeEndDocument ()
void writeEndElement ()
void writeEntityReference (QAnyStringView name )
void writeNamespace (QAnyStringView namespaceUri , QAnyStringView prefix = {})
void writeProcessingInstruction (QAnyStringView target , QAnyStringView data = {})
void writeStartDocument (QAnyStringView version )
void writeStartDocument (QAnyStringView version , bool standalone )
void writeStartDocument ()
void writeStartElement (QAnyStringView namespaceUri , QAnyStringView name )
void writeStartElement (QAnyStringView qualifiedName )
void writeTextElement (QAnyStringView namespaceUri , QAnyStringView name , QAnyStringView text )
void writeTextElement (QAnyStringView qualifiedName , QAnyStringView text )

詳細描述

QXmlStreamWriter 搭檔 QXmlStreamReader for writing XML. It is compliant with the XML 1.0 specification and writes documents using XML 1.0 syntax, escaping rules, and character validity constraints.

注意: XML 1.1 is not supported. While version strings may be set manually in the output, documents requiring features specific to XML 1.1, such as additional control characters cannot be produced using this class.

Like its related class, it operates on a QIODevice 指定采用 setDevice ()。API 簡單明瞭:為想要編寫每個 XML 令牌或事件,寫入器提供專用功能。

開始文檔采用 writeStartDocument () 和結束它采用 writeEndDocument (). This will implicitly close all remaining open tags.

Element tags are opened with writeStartElement () followed by writeAttribute () 或 writeAttributes (), element content, and then writeEndElement (). A shorter form writeEmptyElement () can be used to write empty elements, followed by writeAttributes ().

Element content consists of either characters, entity references or nested elements. It is written with writeCharacters (), which also takes care of escaping all forbidden characters and character sequences, writeEntityReference (), or subsequent calls to writeStartElement (). A convenience method writeTextElement () can be used for writing terminal elements that contain nothing but text.

The following abridged code snippet shows the basic use of the class to write formatted XML with indentation:

    QXmlStreamWriter stream(&output);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    ...
    stream.writeStartElement("bookmark");
    stream.writeAttribute("href", "http://qt-project.org/");
    stream.writeTextElement("title", "Qt Project");
    stream.writeEndElement(); // bookmark
    ...
    stream.writeEndDocument();
					

QXmlStreamWriter takes care of prefixing namespaces, all you have to do is specify the namespaceUri when writing elements or attributes. If you must conform to certain prefixes, you can force the writer to use them by declaring the namespaces manually with either writeNamespace () 或 writeDefaultNamespace (). Alternatively, you can bypass the stream writer's namespace support and use overloaded methods that take a qualified name instead. The namespace http://www.w3.org/XML/1998/namespace is implicit and mapped to the prefix xml .

The stream writer can automatically format the generated XML data by adding line-breaks and indentation to empty sections between elements, making the XML data more readable for humans and easier to work with for most source code management systems. The feature can be turned on with the autoFormatting property, and customized with the autoFormattingIndent 特性。

Other functions are writeCDATA (), writeComment (), writeProcessingInstruction (),和 writeDTD (). Chaining of XML streams is supported with writeCurrentToken ().

QXmlStreamWriter always encodes XML in UTF-8.

If an error occurs while writing, hasError () will return true. However, by default, data that was already buffered at the time the error occurred, or data written from within the same operation, may still be written to the underlying device. This applies to Error::Encoding , Error::InvalidCharacter , and user-raised Error::Custom . To avoid this and ensure no data is written after an error, use the stopWritingOnError property. When this property is enabled, the first error stops output immediately and the writer ignores all subsequent write operations. Applications should treat the error state as terminal and avoid further use of the writer after an error.

The QXmlStream 書簽範例 illustrates how to use a stream writer to write an XML bookmark file (XBEL) that was previously read in by a QXmlStreamReader .

成員類型文檔編製

[since 6.10] enum class QXmlStreamWriter:: Error

This enum specifies the different error cases that can occur when writing XML with QXmlStreamWriter .

常量 描述
QXmlStreamWriter::Error::None 0 沒有齣現錯誤。
QXmlStreamWriter::Error::IO 1 An I/O error occurred while writing to the device.
QXmlStreamWriter::Error::Encoding 2 An encoding error occurred while converting characters to the output format.
QXmlStreamWriter::Error::InvalidCharacter 3 A character not permitted in XML 1.0 was encountered while writing.
QXmlStreamWriter::Error::Custom 4 引發自定義錯誤采有 raiseError ().

This enum was introduced in Qt 6.10.

特性文檔編製

autoFormatting : bool

This property holds the auto-formatting flag of the stream writer.

This property controls whether or not the stream writer automatically formats the generated XML data. If enabled, the writer automatically adds line-breaks and indentation to empty sections between elements (ignorable whitespace). The main purpose of auto-formatting is to split the data into several lines, and to increase readability for a human reader. The indentation depth can be controlled through the autoFormattingIndent 特性。

默認情況下,自動格式化被禁用。

訪問函數:

bool autoFormatting () const
void setAutoFormatting (bool enable )

autoFormattingIndent : int

This property holds the number of spaces or tabs used for indentation when auto-formatting is enabled. Positive numbers indicate spaces, negative numbers tabs.

默認縮進為 4。

訪問函數:

int autoFormattingIndent () const
void setAutoFormattingIndent (int spacesOrTabs )

另請參閱 autoFormatting .

[since 6.10] stopWritingOnError : bool

This property holds the option to stop writing to the device after encountering an error.

若把此特性設為 true , the writer stops writing immediately upon encountering any error and ignores all subsequent write operations. When this property is set to false , the writer may continue writing after an error, skipping the invalid write but allowing further output.

Note that this includes Error::InvalidCharacter , Error::Encoding ,和 Error::Custom . Error::IO is always considered terminal and stops writing regardless of this setting.

默認值為 false .

此特性在 Qt 6.10 引入。

訪問函數:

bool stopWritingOnError () const
void setStopWritingOnError (bool stop )

成員函數文檔編製

QXmlStreamWriter:: QXmlStreamWriter ()

構造流寫入器。

另請參閱 setDevice ().

[explicit] QXmlStreamWriter:: QXmlStreamWriter ( QByteArray * array )

Constructs a stream writer that writes into array . This is the same as creating an xml writer that operates on a QBuffer device which in turn operates on array .

[explicit] QXmlStreamWriter:: QXmlStreamWriter ( QIODevice * device )

Constructs a stream writer that writes into device ;

[explicit] QXmlStreamWriter:: QXmlStreamWriter ( QString * string )

Constructs a stream writer that writes into string .

[noexcept] QXmlStreamWriter:: ~QXmlStreamWriter ()

析構函數。

bool QXmlStreamWriter:: autoFormatting () const

返迴 true if auto formatting is enabled, otherwise false .

注意: getter 函數對於特性 autoFormatting。

另請參閱 setAutoFormatting ().

QIODevice *QXmlStreamWriter:: device () const

返迴被當前設備關聯的 QXmlStreamWriter ,或 nullptr 若沒有設備被賦值。

另請參閱 setDevice ().

[since 6.10] QXmlStreamWriter::Error QXmlStreamWriter:: error () const

Returns the current error state of the writer.

If no error has occurred, this function returns QXmlStreamWriter::Error::None .

該函數在 Qt 6.10 引入。

另請參閱 errorString (), raiseError(const QString &message), and hasError ().

[since 6.10] QString QXmlStreamWriter:: errorString () const

If an error has occurred, returns its associated error message.

The error message is either set internally by QXmlStreamWriter or provided by the user via raiseError (). If no error has occured, this function returns a null string.

該函數在 Qt 6.10 引入。

另請參閱 error (), raiseError(const QString &message), and hasError ().

bool QXmlStreamWriter:: hasError () const

返迴 true if an error occurred while trying to write data.

If the error is Error::IO , subsequent writes to the underlying QIODevice will fail. In other cases malformed data might be written to the document.

The error status is never reset. Writes happening after the error occurred may be ignored, even if the error condition is cleared.

另請參閱 error (), errorString (), and raiseError(const QString &message).

[since 6.10] void QXmlStreamWriter:: raiseError ( QAnyStringView message )

Raises a custom error with the given message .

This function is for manual indication that an error has occurred during writing, such as an application level validation failure.

該函數在 Qt 6.10 引入。

另請參閱 errorString (), error (),和 hasError ().

void QXmlStreamWriter:: setAutoFormatting ( bool enable )

啓用自動格式化若 enable is true ,否則禁用它。

默認值為 false .

注意: setter 函數對於特性 autoFormatting .

另請參閱 autoFormatting ().

void QXmlStreamWriter:: setDevice ( QIODevice * device )

把當前設備設為 device . If you want the stream to write into a QByteArray ,可以創建 QBuffer 設備。

另請參閱 device ().

void QXmlStreamWriter:: writeAttribute ( QAnyStringView namespaceUri , QAnyStringView name , QAnyStringView value )

Writes an attribute with name and value , prefixed for the specified namespaceUri . If the namespace has not been declared yet, QXmlStreamWriter will generate a namespace declaration for it.

This function can only be called after writeStartElement () before any content is written, or after writeEmptyElement ().

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeAttribute (const QXmlStreamAttribute & attribute )

寫入 attribute .

This function can only be called after writeStartElement () before any content is written, or after writeEmptyElement ().

這是重載函數。

void QXmlStreamWriter:: writeAttribute ( QAnyStringView qualifiedName , QAnyStringView value )

Writes an attribute with qualifiedName and value .

This function can only be called after writeStartElement () before any content is written, or after writeEmptyElement ().

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

這是重載函數。

void QXmlStreamWriter:: writeAttributes (const QXmlStreamAttributes & 屬性 )

Writes the attribute vector attributes . If a namespace referenced in an attribute not been declared yet, QXmlStreamWriter will generate a namespace declaration for it.

This function can only be called after writeStartElement () before any content is written, or after writeEmptyElement ().

另請參閱 writeAttribute () 和 writeNamespace ().

void QXmlStreamWriter:: writeCDATA ( QAnyStringView text )

寫入 text as CDATA section. If text contains the forbidden character sequence "]]>", it is split into different CDATA sections.

This function mainly exists for completeness. Normally you should not need use it, because writeCharacters () automatically escapes all non-content characters.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeCharacters ( QAnyStringView text )

寫入 text . The characters "<", "&", and """ are escaped as entity references "<", "&, and """. To avoid the forbidden sequence "]]>", ">" is also escaped as ">".

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

另請參閱 writeEntityReference ().

void QXmlStreamWriter:: writeComment ( QAnyStringView text )

寫入 text as XML comment, where text must not contain the forbidden sequence -- or end with - . Note that XML does not provide any way to escape - in a comment.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeCurrentToken (const QXmlStreamReader & reader )

Writes the current state of the reader . All possible valid states are supported.

The purpose of this function is to support chained processing of XML data.

另請參閱 QXmlStreamReader::tokenType ().

void QXmlStreamWriter:: writeDTD ( QAnyStringView dtd )

Writes a DTD section. The dtd represents the entire doctypedecl production from the XML 1.0 specification.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeDefaultNamespace ( QAnyStringView namespaceUri )

Writes a default namespace declaration for namespaceUri .

writeStartElement () 或 writeEmptyElement () was called, the declaration applies to the current element; otherwise it applies to the next child element.

Note that the namespaces http://www.w3.org/XML/1998/namespace (bound to xmlns ) 和 http://www.w3.org/2000/xmlns/ (bound to xml ) by definition cannot be declared as default.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeEmptyElement ( QAnyStringView namespaceUri , QAnyStringView name )

Writes an empty element with name , prefixed for the specified namespaceUri . If the namespace has not been declared, QXmlStreamWriter will generate a namespace declaration for it. Subsequent calls to writeAttribute () will add attributes to this element.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

另請參閱 writeNamespace ().

void QXmlStreamWriter:: writeEmptyElement ( QAnyStringView qualifiedName )

Writes an empty element with qualified name qualifiedName . Subsequent calls to writeAttribute () will add attributes to this element.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

這是重載函數。

void QXmlStreamWriter:: writeEndDocument ()

Closes all remaining open start elements and writes a newline.

另請參閱 writeStartDocument ().

void QXmlStreamWriter:: writeEndElement ()

Closes the previous start element.

另請參閱 writeStartElement ().

void QXmlStreamWriter:: writeEntityReference ( QAnyStringView name )

Writes the entity reference name to the stream, as "& name ;".

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeNamespace ( QAnyStringView namespaceUri , QAnyStringView prefix = {})

Writes a namespace declaration for namespaceUri with prefix 。若 prefix is empty, QXmlStreamWriter assigns a unique prefix consisting of the letter 'n' followed by a number.

writeStartElement () 或 writeEmptyElement () was called, the declaration applies to the current element; otherwise it applies to the next child element.

Note that the prefix xml is both predefined and reserved for http://www.w3.org/XML/1998/namespace , which in turn cannot be bound to any other prefix. The prefix xmlns and its URI http://www.w3.org/2000/xmlns/ are used for the namespace mechanism itself and thus completely forbidden in declarations.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeProcessingInstruction ( QAnyStringView target , QAnyStringView data = {})

Writes an XML processing instruction with target and data ,其中 data must not contain the sequence "?>".

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeStartDocument ( QAnyStringView version )

Writes a document start with the XML version number version .

注意: This function does not validate the version string and allows setting it manually. However, QXmlStreamWriter only supports XML 1.0. Setting a version string other than "1.0" does not change the writer's behavior or escaping rules. It is the caller's responsibility to ensure consistency between the declared version and the actual content.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

另請參閱 writeEndDocument ().

void QXmlStreamWriter:: writeStartDocument ( QAnyStringView version , bool standalone )

Writes a document start with the XML version number version and a standalone attribute standalone .

注意: This function does not validate the version string and allows setting it manually. However, QXmlStreamWriter only supports XML 1.0. Setting a version string other than "1.0" does not change the writer's behavior or escaping rules. It is the caller's responsibility to ensure consistency between the declared version and the actual content.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

另請參閱 writeEndDocument ().

void QXmlStreamWriter:: writeStartDocument ()

Writes a document start with XML version number "1.0".

這是重載函數。

另請參閱 writeEndDocument ().

void QXmlStreamWriter:: writeStartElement ( QAnyStringView namespaceUri , QAnyStringView name )

Writes a start element with name , prefixed for the specified namespaceUri . If the namespace has not been declared yet, QXmlStreamWriter will generate a namespace declaration for it. Subsequent calls to writeAttribute () will add attributes to this element.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

另請參閱 writeNamespace (), writeEndElement (),和 writeEmptyElement ().

void QXmlStreamWriter:: writeStartElement ( QAnyStringView qualifiedName )

Writes a start element with qualifiedName . Subsequent calls to writeAttribute () will add attributes to this element.

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

這是重載函數。

另請參閱 writeEndElement () 和 writeEmptyElement ().

void QXmlStreamWriter:: writeTextElement ( QAnyStringView namespaceUri , QAnyStringView name , QAnyStringView text )

Writes a text element with name , prefixed for the specified namespaceUri ,和 text . If the namespace has not been declared, QXmlStreamWriter will generate a namespace declaration for it.

This is a convenience function equivalent to:

        writeStartElement(namespaceUri, name);
        writeCharacters(text);
        writeEndElement();
					

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

void QXmlStreamWriter:: writeTextElement ( QAnyStringView qualifiedName , QAnyStringView text )

Writes a text element with qualifiedName and text .

This is a convenience function equivalent to:

        writeStartElement(qualifiedName);
        writeCharacters(text);
        writeEndElement();
					

注意: In Qt versions prior to 6.5, this function took QString , not QAnyStringView .

這是重載函數。