Qt: QXmlStreamWriter Class写XML文件

前端之家收集整理的这篇文章主要介绍了Qt: QXmlStreamWriter Class写XML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

需求:

使用QXMLStreamWriter,将如下界面的结构写入XML文件



效果



思路:

1、先构造树形控件treeWidget.

2、使用QXMLStreamWriter,写XML文件


源码:

#include <QApplication>
#include <QXmlStreamWriter>
#include <QFile>
#include <QDebug>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QHeaderView>

void populateTree(QTreeWidget *treeWidget)//构造树
{
    treeWidget->setHeaderLabels(QStringList()<<"Terms" <<"Pages");
    treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch);
    treeWidget->setWindowTitle(QObject::tr("XML Stream Writer"));
    treeWidget->show();

    (void) new QTreeWidgetItem(treeWidget,QStringList() << "sidebearings" << "10,34-35,307-308");
    QTreeWidgetItem *subTerm = new QTreeWidgetItem(treeWidget,QStringList() << "subtraction");
    (void) new QTreeWidgetItem(subTerm,QStringList() << "of pictures" << "115,244");
    (void) new QTreeWidgetItem(subTerm,QStringList() << "of vectors" << "9");
}

void writeIndexEntry(QXmlStreamWriter *xmlWriter,QTreeWidgetItem *item )
{
    xmlWriter->writeStartElement("entry");;
    xmlWriter->writeAttribute("term",item->text(0));

    QString pageString = item->text(1);
    if(!pageString.isEmpty())
    {
        QStringList pages = pageString.split(",");
        foreach (QString page,pages) {
            xmlWriter->writeTextElement("page",page);
        }
    }
    for(int i=0; i<item->childCount() ; ++i)
        writeIndexEntry(xmlWriter,item->child(i));

    xmlWriter->writeEndElement();
}

bool writeXml(const QString &fileName,QTreeWidget *treeWidget)
{
    QFile file(fileName);
    if(!file.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug()<< "Error: Cannot write file "
                <<fileName
               <<": "
              <<file.errorString();
        return false;
    }
    QXmlStreamWriter xmlWriter(&file);
    xmlWriter.setAutoFormatting(true);
    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement("bookindex");
    qDebug()<<"1: "<<treeWidget->topLevelItemCount();
    for(int i=0 ; i< treeWidget->topLevelItemCount() ; ++i)
        writeIndexEntry(&xmlWriter,treeWidget->topLevelItem(i));
    xmlWriter.writeEndDocument();

    file.close();
    if(file.error())
    {
        qDebug()<<"Error: Cannot write file "
               << fileName << ": "
               << file.errorString();
        return false;
    }
    return true;
}

int main(int argc,char *argv[])
{
    QApplication a(argc,argv);

    QTreeWidget treeWidget;
    populateTree(&treeWidget);
    writeXml("out1.xml",&treeWidget);

    return a.exec();
}
原文链接:https://www.f2er.com/xml/294675.html

猜你在找的XML相关文章