搞个简单点的xml写入,可以直接运行的
#-------------------------------------------------
#
# Project created by QtCreator 2022-10-31T14:10:02
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = untitled
TEMPLATE = app
SOURCES += main.cpp\
widget.cpp
HEADERS += widget.h
FORMS += widget.ui
QT += xml
#ifndef WIDGET_H
#define WIDGET_H
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void init();
void write();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
#include
#include
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
init();
write();
return;
}
void Widget::write()
{
QFile file("food.xml");
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("open food.xml fail!"),QMessageBox::Ok);
return;
}
QDomDocument domDocument;
if (!domDocument.setContent(&file, true)){
QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("domDocument.setContent fail!"),QMessageBox::Ok);
file.close();
return;
}
QDomDocument xDoc;
QDomElement docElem = domDocument.documentElement();
QDomNode lastNode = docElem.lastChild();
//在lastitem上添加一个节点
QDomElement NodeItem = domDocument.createElement("Node");
QDomElement SoftNameItem = domDocument.createElement("SoftName");
SoftNameItem.appendChild(xDoc.createTextNode(""));
NodeItem.appendChild(SoftNameItem);
//添加元素节点到父节点
docElem.appendChild(NodeItem);
file.close();
QFile fileModify("food.xml");
if (!fileModify.open(QFile::WriteOnly | QFile::Text)){
QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("fileModify food.xml fail"),QMessageBox::Ok);
return;
}
QTextStream out(&fileModify);
domDocument.save(out,4);
fileModify.close();
return;
}
void Widget::init()
{
QFile file("food.xml");
if(file.open(QIODevice::ReadOnly)){
file.close();
return;
}
if(!file.open(QIODevice::ReadWrite)){
QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("open food.xml fail!"),QMessageBox::Ok);
return;
}
QDomDocument domDocument;
QDomProcessingInstruction pro = domDocument.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
domDocument.appendChild(pro);
QDomElement root = domDocument.createElement("hard");
domDocument.appendChild(root);
QTextStream out(&file);
domDocument.save(out,4);
file.close();
}
Widget::~Widget()
{
delete ui;
}