Описание класса QXmlStreamWriter [Модуль QtCore]
Класс QXmlStreamWriter представляет XML писателя с простым потоковым API. Далее...
#include <QXmlStreamWriter> Замечание: все функции этого класса реентерабильны.
Класс был добавлен в Qt 4.3.
Свойства
Открытые функции
- QXmlStreamWriter ()
- QXmlStreamWriter ( QIODevice * device )
- QXmlStreamWriter ( QByteArray * array )
- QXmlStreamWriter ( QString * string )
- ~QXmlStreamWriter ()
- bool autoFormatting () const
- int autoFormattingIndent () const
- QTextCodec * codec () const
- QIODevice * device () const
- void setAutoFormatting ( bool enable )
- void setAutoFormattingIndent ( int spaces )
- void setCodec ( QTextCodec * codec )
- void setCodec ( const char * codecName )
- void setDevice ( QIODevice * device )
- void writeAttribute ( const QString & namespaceUri, const QString & name, const QString & value )
- void writeAttribute ( const QString & qualifiedName, const QString & value )
- void writeAttribute ( const QXmlStreamAttribute & attribute )
- void writeAttributes ( const QXmlStreamAttributes & attributes )
- void writeCDATA ( const QString & text )
- void writeCharacters ( const QString & text )
- void writeComment ( const QString & text )
- void writeCurrentToken ( const QXmlStreamReader & reader )
- void writeDTD ( const QString & dtd )
- void writeDefaultNamespace ( const QString & namespaceUri )
- void writeEmptyElement ( const QString & namespaceUri, const QString & name )
- void writeEmptyElement ( const QString & qualifiedName )
- void writeEndDocument ()
- void writeEndElement ()
- void writeEntityReference ( const QString & name )
- void writeNamespace ( const QString & namespaceUri, const QString & prefix = QString() )
- void writeProcessingInstruction ( const QString & target, const QString & data = QString() )
- void writeStartDocument ( const QString & version )
- void writeStartDocument ()
- void writeStartElement ( const QString & namespaceUri, const QString & name )
- void writeStartElement ( const QString & qualifiedName )
- void writeTextElement ( const QString & namespaceUri, const QString & name, const QString & text )
- void writeTextElement ( const QString & qualifiedName, const QString & text )
Подробное описание
Класс QXmlStreamWriter представляет XML писателя с простым потоковым API.
QXmlStreamWriter работает в связке с QXmlStreamReader для записи XML. Как и связанный класс, он работает с QIODevice, определённым с помощью setDevice(). The API is simple and straight forward: 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 with writeEndDocument(). This will implicitly close all remaining open tags.
Element tags are opened with writeStartElement() followed by writeAttribute() or 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.
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() or 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 property.
Other functions are writeCDATA(), writeComment(), writeProcessingInstruction(), and writeDTD(). Chaining of XML streams is supported with writeCurrentToken().
By default, QXmlStreamWriter encodes XML in UTF-8. Different encodings can be enforced using setCodec().
The QXmlStream Bookmarks Example illustrates how to use a subclassed stream writer to write an XML bookmark file (XBEL) that was previously read in by a QXmlStreamReader.
Описание свойств
autoFormatting : bool
флаг автоматического форматирования потокового писателя
Это свойство определяет, будет ли писатель автоматически форматировать созданные XML данные. Если оно включено, писатель автоматически добавляет переходы на новую строку и отступы между элементами (игнорируемые символы пустого пространства). Главная цель автоматического форматирования - разбить данные на несколько строк и улучшить удобочитаемость для человека. Глубина отступов может быть настроена с помощью свойства autoFormattingIndent.
По умолчанию автоматическое форматирование выключено.
Это свойство было введено в Qt 4.4.
Функции доступа:
- bool autoFormatting () const
- void setAutoFormatting ( bool enable )
autoFormattingIndent : int
Это свойство хранит количество пробелов, используемых для отступов, если автоматическое форматирование включено.
По умолчанию равно 4.
Это свойство было введено в Qt 4.4.
Функции доступа:
- int autoFormattingIndent () const
- void setAutoFormattingIndent ( int spaces )
Смотрите также autoFormatting.
Описание функций-членов
QXmlStreamWriter::QXmlStreamWriter ()
Создаёт потокового писателя.
Смотрите также setDevice().
QXmlStreamWriter::QXmlStreamWriter ( QIODevice * device )
Создаёт потокового писателя, который пишет в device;
QXmlStreamWriter::QXmlStreamWriter ( QByteArray * array )
Создаёт потокового писателя, который пишет в array. Это то же самое, если создать xml писателя, который работает с устройством QBuffer, которое, в свою очередь, работает с array.
QXmlStreamWriter::QXmlStreamWriter ( QString * string )
Создаёт потокового писателя, который пишет в string.
QXmlStreamWriter::~QXmlStreamWriter ()
Деструктор.
QTextCodec * QXmlStreamWriter::codec () const
Возвращает кодек, который в данный момент связан с потоком.
Смотрите также setCodec().
QIODevice * QXmlStreamWriter::device () const
Возвращает текущее устройство, которое связано с QXmlStreamWriter, или 0, если такого нет.
Смотрите также setDevice().
void QXmlStreamWriter::setCodec ( QTextCodec * codec )
Устанавливает кодет для текущего потока в codec. Данный кодек используется для кодирования всех записываемых данных. По умолчанию QXmlStreamWriter использует UTF-8.
Смотрите также codec().
void QXmlStreamWriter::setCodec ( const char * codecName )
Это перегруженная функция, предоставленная для удобства.
Sets the codec for this stream to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.
See also QTextCodec::codecForName().
void QXmlStreamWriter::setDevice ( QIODevice * device )
Устанавливает текущее устройство в device. If you want the stream to write into a QByteArray, you can create a QBuffer device.
See also device().
void QXmlStreamWriter::writeAttribute ( const QString & namespaceUri, const QString & name, const QString & 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().
void QXmlStreamWriter::writeAttribute ( const QString & qualifiedName, const QString & value )
Это перегруженная функция, предоставленная для удобства.
Writes an attribute with qualifiedName and value.
This function can only be called after writeStartElement() before any content is written, or after writeEmptyElement().
void QXmlStreamWriter::writeAttribute ( const QXmlStreamAttribute & attribute )
Это перегруженная функция, предоставленная для удобства.
Writes the attribute.
This function can only be called after writeStartElement() before any content is written, or after writeEmptyElement().
void QXmlStreamWriter::writeAttributes ( const QXmlStreamAttributes & attributes )
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().
See also writeAttribute() and writeNamespace().
void QXmlStreamWriter::writeCDATA ( const QString & text )
Writes 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.
void QXmlStreamWriter::writeCharacters ( const QString & text )
Writes text. The characters "<", "&", and """ are escaped as entity references "<", "&, and """. To avoid the forbidden sequence "]]>", ">" is also escaped as ">".
See also writeEntityReference().
void QXmlStreamWriter::writeComment ( const QString & text )
Writes 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.
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.
See also QXmlStreamReader::tokenType().
void QXmlStreamWriter::writeDTD ( const QString & dtd )
Writes a DTD section. The dtd represents the entire doctypedecl production from the XML 1.0 specification.
void QXmlStreamWriter::writeDefaultNamespace ( const QString & namespaceUri )
Writes a default namespace declaration for namespaceUri.
If writeStartElement() or 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) and http://www.w3.org/2000/xmlns/ (bound to xml) by definition cannot be declared as default.
void QXmlStreamWriter::writeEmptyElement ( const QString & namespaceUri, const QString & 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. Последующий вызов writeAttribute() добавит атрибут к этому элементу.
Смотрите также writeNamespace().
void QXmlStreamWriter::writeEmptyElement ( const QString & qualifiedName )
Это перегруженная функция, предоставленная для удобства.
Записывает пустой элемент с полным именем qualifiedName. Последующий вызов writeAttribute() добавит атрибут к этому элементу.
void QXmlStreamWriter::writeEndDocument ()
Закрывает все открытые элементы и добавляет переход на новую строку.
Смотрите также writeStartDocument().
void QXmlStreamWriter::writeEndElement ()
Закрывает предыдущий открытый элемент.
Смотрите также writeStartElement().
void QXmlStreamWriter::writeEntityReference ( const QString & name )
Записывает описание сущности name в поток, как "&name;".
void QXmlStreamWriter::writeNamespace ( const QString & namespaceUri, const QString & prefix = QString() )
Writes a namespace declaration for namespaceUri with prefix. If prefix is empty, QXmlStreamWriter assigns a unique prefix consisting of the letter 'n' followed by a number.
If writeStartElement() or 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.
void QXmlStreamWriter::writeProcessingInstruction ( const QString & target, const QString & data = QString() )
Записывает инструкцию обработки XML с целью target и данными data, где data не должны содержать последовательность символов "?>".
void QXmlStreamWriter::writeStartDocument ( const QString & version )
Записывает начало XML документа версии version.
Смотрите также writeEndDocument().
void QXmlStreamWriter::writeStartDocument ()
Это перегруженная функция, предоставленная для удобства.
Записывает начало XML документа версии "1.0"
Смотрите также writeEndDocument().
void QXmlStreamWriter::writeStartElement ( const QString & namespaceUri, const QString & name )
Записывает начальный элемент с именем name и префиксом указанного namespaceUri. Если пространство имён ещё не было объявлено, QXmlStreamWriter сгенерирует для него декларацию. Последующий вызов writeAttribute() добавит атрибут к этому элементу.
Смотрите также writeNamespace(), writeEndElement() и writeEmptyElement().
void QXmlStreamWriter::writeStartElement ( const QString & qualifiedName )
Это перегруженная функция, предоставленная для удобства.
Записывает начальных элемент с полным именем qualifiedName. Последующий вызов writeAttribute() добавит атрибут к этому элементу.
Смотрите также writeEndElement() и writeEmptyElement().
void QXmlStreamWriter::writeTextElement ( const QString & namespaceUri, const QString & name, const QString & text )
Записывает текстовый элемент с именем name и префиксом или с URI namespaceUri и содержимым text. Если пространство имён не было объявлено, QXmlStreamWriter сгенерирует его декларацию.
Эта вспомогательная функция эквивалентна:
writeStartElement(namespaceUri, name);
writeCharacters(text);
writeEndElement();
void QXmlStreamWriter::writeTextElement ( const QString & qualifiedName, const QString & text )
Это перегруженная функция, предоставленная для удобства.
Записывает текстовый элемент с полным именем qualifiedName и содержимым text.
Эта вспомогательная функция эквивалентна:
writeStartElement(qualifiedName);
writeCharacters(text);
writeEndElement();
|