PySide6.QtCore.QXmlStreamWriter¶
- class QXmlStreamWriter¶
The
QXmlStreamWriter
class provides an XML 1.0 writer with a simple streaming API.Details
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QXmlStreamWriter
is the counterpart toQXmlStreamReader
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.Note
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
specified withsetDevice()
. The API is simple and straightforward: for every XML token or event you want to write, the writer provides a specialized function.You start a document with
writeStartDocument()
and end it withwriteEndDocument()
. This will implicitly close all remaining open tags.Element tags are opened with
writeStartElement()
followed bywriteAttribute()
orwriteAttributes()
, element content, and thenwriteEndElement()
. A shorter formwriteEmptyElement()
can be used to write empty elements, followed bywriteAttributes()
.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 towriteStartElement()
. A convenience methodwriteTextElement()
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:
stream = QXmlStreamWriter(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 thenamespaceUri
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 eitherwriteNamespace()
orwriteDefaultNamespace()
. 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 theautoFormattingIndent
property.Other functions are
writeCDATA()
,writeComment()
,writeProcessingInstruction()
, andwriteDTD()
. Chaining of XML streams is supported withwriteCurrentToken()
.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 toEncoding
,InvalidCharacter
, and user-raisedCustom
. To avoid this and ensure no data is written after an error, use thestopWritingOnError
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 Bookmarks Example illustrates how to use a stream writer to write an XML bookmark file (XBEL) that was previously read in by a
QXmlStreamReader
.Synopsis¶
Methods¶
def
__init__()
def
autoFormatting()
def
device()
def
error()
def
errorString()
def
hasError()
def
raiseError()
def
setDevice()
def
writeAttribute()
def
writeCDATA()
def
writeComment()
def
writeDTD()
def
writeNamespace()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
- class Error¶
This enum specifies the different error cases that can occur when writing XML with
QXmlStreamWriter
.Constant
Description
QXmlStreamWriter.Error.Error.None_
No error has occurred.
QXmlStreamWriter.Error.Error.IO
An I/O error occurred while writing to the device.
QXmlStreamWriter.Error.Error.Encoding
An encoding error occurred while converting characters to the output format.
QXmlStreamWriter.Error.Error.InvalidCharacter
A character not permitted in XML 1.0 was encountered while writing.
QXmlStreamWriter.Error.Error.Custom
A custom error has been raised with
raiseError()
.Added in version 6.10.
- __init__()¶
Constructs a stream writer.
See also
- __init__(array)
- Parameters:
array –
QByteArray
Constructs a stream writer that writes into
array
. This is the same as creating an xml writer that operates on aQBuffer
device which in turn operates onarray
.- __init__(device)
- Parameters:
device –
QIODevice
Constructs a stream writer that writes into
device
;- autoFormatting()¶
- Return type:
bool
Returns
true
if auto formatting is enabled, otherwisefalse
.See also
- autoFormattingIndent()¶
- Return type:
int
See also
Returns the current device associated with the
QXmlStreamWriter
, orNone
if no device has been assigned.See also
Returns the current error state of the writer.
If no error has occurred, this function returns
None
.See also
- errorString()¶
- Return type:
str
If an error has occurred, returns its associated error message.
The error message is either set internally by
QXmlStreamWriter
or provided by the user viaraiseError()
. If no error has occured, this function returns a null string.See also
- hasError()¶
- Return type:
bool
Returns
true
if an error occurred while trying to write data.If the error is
IO
, subsequent writes to the underlyingQIODevice
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.
See also
error()
errorString()
raiseError(const QString &message)
- raiseError(message)¶
- Parameters:
message – str
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.
See also
- setAutoFormatting(enable)¶
- Parameters:
enable – bool
Enables auto formatting if
enable
istrue
, otherwise disables it.The default value is
false
.See also
- setAutoFormattingIndent(spacesOrTabs)¶
- Parameters:
spacesOrTabs – int
See also
Sets the current device to
device
. If you want the stream to write into aQByteArray
, you can create aQBuffer
device.See also
- setStopWritingOnError(stop)¶
- Parameters:
stop – bool
See also
- stopWritingOnError()¶
- Return type:
bool
See also
- writeAttribute(attribute)¶
- Parameters:
attribute –
QXmlStreamAttribute
Writes the
attribute
.This function can only be called after
writeStartElement()
before any content is written, or afterwriteEmptyElement()
.- writeAttribute(qualifiedName, value)
- Parameters:
qualifiedName – str
value – str
Writes an attribute with
qualifiedName
andvalue
.This function can only be called after
writeStartElement()
before any content is written, or afterwriteEmptyElement()
.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeAttribute(namespaceUri, name, value)
- Parameters:
namespaceUri – str
name – str
value – str
Writes an attribute with
name
andvalue
, prefixed for the specifiednamespaceUri
. 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 afterwriteEmptyElement()
.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeAttributes(attributes)¶
- Parameters:
attributes –
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 afterwriteEmptyElement()
.See also
- writeCDATA(text)¶
- Parameters:
text – str
Writes
text
as CDATA section. Iftext
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.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeCharacters(text)¶
- Parameters:
text – str
Writes
text
. The characters “<”, “&”, and “”” are escaped as entity references “<”, “&, and “"”. To avoid the forbidden sequence “]]>”, “>” is also escaped as “>”.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.See also
- writeComment(text)¶
- Parameters:
text – str
Writes
text
as XML comment, wheretext
must not contain the forbidden sequence--
or end with-
. Note that XML does not provide any way to escape-
in a comment.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeCurrentToken(reader)¶
- Parameters:
reader –
QXmlStreamReader
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.
See also
- writeDTD(dtd)¶
- Parameters:
dtd – str
Writes a DTD section. The
dtd
represents the entire doctypedecl production from the XML 1.0 specification.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeDefaultNamespace(namespaceUri)¶
- Parameters:
namespaceUri – str
Writes a default namespace declaration for
namespaceUri
.If
writeStartElement()
orwriteEmptyElement()
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) and http://www.w3.org/2000/xmlns/ (bound to xml) by definition cannot be declared as default.
Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeEmptyElement(qualifiedName)¶
- Parameters:
qualifiedName – str
Writes an empty element with qualified name
qualifiedName
. Subsequent calls towriteAttribute()
will add attributes to this element.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeEmptyElement(namespaceUri, name)
- Parameters:
namespaceUri – str
name – str
Writes an empty element with
name
, prefixed for the specifiednamespaceUri
. If the namespace has not been declared,QXmlStreamWriter
will generate a namespace declaration for it. Subsequent calls towriteAttribute()
will add attributes to this element.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.See also
- writeEndDocument()¶
Closes all remaining open start elements and writes a newline.
See also
- writeEndElement()¶
Closes the previous start element.
See also
- writeEntityReference(name)¶
- Parameters:
name – str
Writes the entity reference
name
to the stream, as “&``name``;”.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeNamespace(namespaceUri[, prefix={}])¶
- Parameters:
namespaceUri – str
prefix – str
Writes a namespace declaration for
namespaceUri
withprefix
. Ifprefix
is empty,QXmlStreamWriter
assigns a unique prefix consisting of the letter ‘n’ followed by a number.If
writeStartElement()
orwriteEmptyElement()
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.
Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeProcessingInstruction(target[, data={}])¶
- Parameters:
target – str
data – str
Writes an XML processing instruction with
target
anddata
, wheredata
must not contain the sequence “?>”.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeStartDocument()¶
Writes a document start with XML version number “1.0”.
See also
- writeStartDocument(version)
- Parameters:
version – str
Writes a document start with the XML version number
version
.Note
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.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.See also
- writeStartDocument(version, standalone)
- Parameters:
version – str
standalone – bool
Writes a document start with the XML version number
version
and a standalone attributestandalone
.Note
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.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.See also
- writeStartElement(qualifiedName)¶
- Parameters:
qualifiedName – str
Writes a start element with
qualifiedName
. Subsequent calls towriteAttribute()
will add attributes to this element.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.See also
- writeStartElement(namespaceUri, name)
- Parameters:
namespaceUri – str
name – str
Writes a start element with
name
, prefixed for the specifiednamespaceUri
. If the namespace has not been declared yet,QXmlStreamWriter
will generate a namespace declaration for it. Subsequent calls towriteAttribute()
will add attributes to this element.Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeTextElement(qualifiedName, text)¶
- Parameters:
qualifiedName – str
text – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Writes a text element with
qualifiedName
andtext
.This is a convenience function equivalent to:
writeStartElement(qualifiedName) writeCharacters(text) writeEndElement()
Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.- writeTextElement(namespaceUri, name, text)
- Parameters:
namespaceUri – str
name – str
text – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Writes a text element with
name
, prefixed for the specifiednamespaceUri
, andtext
. 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()
Note
In Qt versions prior to 6.5, this function took
QString
, notQAnyStringView
.