QT5自学教程(72)——xml Editor
利用前面两节介绍的读写xml的知识,在这一节实现一个简单xml编辑器。下面给出我们的简单例子。
[1]建立一个gui项目
[2]在窗口中添加一个tree view控件和一个PushButton控件
[3]在项目中添加必要的程序
dialog.h程序
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QDebug> #include <QFile> #include <QStandardItemModel> #include <QDomDocument> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private slots: void on_pushButton_clicked(); private: Ui::Dialog *ui; QStandardItemModel *model; QString fileName; void ReadFile(); void WriteFile(); }; #endif // DIALOG_H
dialog.cpp程序
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent),ui(new Ui::Dialog) { ui->setupUi(this); fileName = "F:/test.xml"; model = new QStandardItemModel(0,1,this); ReadFile(); ui->treeView->setModel(model); } Dialog::~Dialog() { delete ui; } //Read XML void Dialog::ReadFile() { QStandardItem *root = new QStandardItem("Books"); model->appendRow(root); QDomDocument doc; //Load the xml file QFile file(fileName); if(file.open(QIODevice::ReadOnly | QIODevice::Text)) { doc.setContent(&file); file.close(); } //get xml root element QDomElement xmlRoot = doc.firstChildElement(); //Read the book QDomNodeList books = xmlRoot.elementsByTagName("Book"); for(int i = 0; i < books.count(); ++i) { QDomElement book = books.at(i).toElement(); QStandardItem *bookItem = new QStandardItem(book.attribute("Name")); //Read the Chapter of the book QDomNodeList chapters = book.elementsByTagName("Chapter"); for(int h = 0; h < chapters.count(); ++h) { QDomElement chapter = chapters.at(h).toElement(); QStandardItem *chapterItem = new QStandardItem(chapter.attribute("Name")); bookItem->appendRow(chapterItem); } root->appendRow(bookItem); } } //Write XML void Dialog::WriteFile() { //Write the xml file QDomDocument doc; //Make a root node QDomElement xmlRoot = doc.createElement("Books"); doc.appendChild(xmlRoot); QStandardItem *root = model->item(0,0); for(int i = 0; i < root->rowCount(); ++i) { QStandardItem *book = root->child(i,0); QDomElement xmlBook = doc.createElement("Book"); xmlBook.setAttribute("Name",book->text()); xmlBook.setAttribute("ID",i); xmlRoot.appendChild(xmlBook); for(int h = 0; h < book->rowCount(); ++h) { QStandardItem *chapter = book->child(h,0); QDomElement xmlChapter = doc.createElement("Chapter"); xmlChapter.setAttribute("Name",chapter->text()); xmlChapter.setAttribute("ID",i); xmlBook.appendChild(xmlChapter); } } //Save to disk QFile file(fileName); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Failed to write file"; } QTextStream out(&file); out << doc.toString(); out.flush(); file.close(); qDebug() << "Finished"; } void Dialog::on_pushButton_clicked() { //Save WriteFile(); }
[4]输出结果
(1)原始xml打开后显示
(2)在窗口修改xml相关项之后点击save,关闭应用,再次打开应用后显示如下
小结
这一节实现了一个简单xml编辑器应用程序。PS: 今天浑身酸痛,可能做得事情有点多再加上昨天打了三个小时篮球,效率很低诶。那今天就先到这里好了o(╯□╰)o
2014/9/16
Wayne HDU
原文链接:https://www.f2er.com/xml/298011.html