QXmlStream Bookmarks Example▲
The QXmlStream Bookmarks example provides a reader for XML Bookmark Exchange Language (XBEL) files using Qt's QXmlStreamReader class for reading, and QXmlStreamWriter class for writing the files.
XbelWriter Class Definition▲
The XbelWriter class contains a private instance of QXmlStreamWriter, which provides an XML writer with a streaming API. XbelWriter also has a reference to the QTreeWidget instance where the bookmark hierarchy is stored.
class XbelWriter
{
public:
explicit XbelWriter(const QTreeWidget *treeWidget);
bool writeFile(QIODevice *device);
private:
void writeItem(const QTreeWidgetItem *item);
QXmlStreamWriter xml;
const QTreeWidget *treeWidget;
};XbelWriter Class Implementation▲
The XbelWriter constructor accepts a treeWidget to initialize within its definition. We enable QXmlStreamWriter's auto-formatting property to ensure line-breaks and indentations are added automatically to empty sections between elements, increasing readability as the data is split into several lines.
XbelWriter::XbelWriter(const QTreeWidget *treeWidget)
: treeWidget(treeWidget)
{
xml.setAutoFormatting(true);
}The writeFile() function accepts a QIODevice object and sets it using setDevice(). This function then writes the document type definition(DTD), the start element, the version, and treeWidget's top-level items.
bool XbelWriter::writeFile(QIODevice *device)
{
xml.setDevice(device);
xml.writeStartDocument();
xml.writeDTD(QStringLiteral("<!DOCTYPE xbel>"));
xml.writeStartElement(QStringLiteral("xbel"));
xml.writeAttribute(XbelReader::versionAttribute(), QStringLiteral("1.0"));
for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
writeItem(treeWidget->topLevelItem(i));
xml.writeEndDocument();
return true;
}The writeItem() function accepts a QTreeWidgetItem object and writes it to the stream, depending on its tagName, which can either be a "folder", "bookmark", or "separator".
void XbelWriter::writeItem(const QTreeWidgetItem *item)
{
QString tagName = item->data(0, Qt::UserRole).toString();
if (tagName == QLatin1String("folder")) {
bool folded = !item->isExpanded();
xml.writeStartElement(tagName);
xml.writeAttribute(XbelReader::foldedAttribute(), folded ? yesValue() : noValue());
xml.writeTextElement(titleElement(), item->text(0));
for (int i = 0; i < item->childCount(); ++i)
writeItem(item->child(i));
xml.writeEndElement();
} else if (tagName == QLatin1String("bookmark")) {
xml.writeStartElement(tagName);
if (!item->text(1).isEmpty())
xml.writeAttribute(XbelReader::hrefAttribute(), item->text(


