首先参考链接:
https://blog.csdn.net/wj584652425/article/details/124333804
源代码:
QFile file("../softwareconfig.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");
QDomElement SoftVersionItem = domDocument.createElement("SoftVersion");
QDomElement SoftParameterItem = domDocument.createElement("SoftParameter");
QDomElement SoftImgItem = domDocument.createElement("SoftImg");
QDomElement SoftAddressItem = domDocument.createElement("SoftAddress");
SoftNameItem.appendChild(xDoc.createTextNode(ui->m_softNameInput->text()));
SoftVersionItem.appendChild(xDoc.createTextNode(ui->m_softVersionInput->text()));
SoftParameterItem.appendChild(xDoc.createTextNode(ui->m_softParameterInput->text()));
SoftImgItem.appendChild(xDoc.createTextNode(ui->m_softImgInput->text()));
SoftAddressItem.appendChild(xDoc.createTextNode(ui->m_softAddressInput->text()));
NodeItem.appendChild(SoftNameItem);
NodeItem.appendChild(SoftVersionItem);
NodeItem.appendChild(SoftParameterItem);
NodeItem.appendChild(SoftImgItem);
NodeItem.appendChild(SoftAddressItem);
//添加元素节点到父节点
docElem.appendChild(NodeItem);
file.close();
QFile fileModify("../softwareconfig.xml");
if (!fileModify.open(QFile::WriteOnly | QFile::Text)){
QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("fileModify ../softwareconfig.xml fail"),QMessageBox::Ok);
return;
}
QTextStream out(&fileModify);
domDocument.save(out,4);
fileModify.close();
return;
生成如下xml:
<?xml version="1.0" encoding="utf-8"?>
<hard>
<Node>
<SoftName>航电建模软件</SoftName>
<SoftVersion>1.1.1</SoftVersion>
<SoftParameter>null</SoftParameter>
<SoftImg>c:/img</SoftImg>
<SoftAddress>c:/data</SoftAddress>
</Node>
</hard>